当前位置:网站首页>laravel-practice
laravel-practice
2022-08-08 16:32:00 【Filariasis like summer xx】
安装laravel
composer create-project --prefer-dist laravel/laravel larabbs "8.*"
查看版本号
php artisan --version
伪静态
location / {
try_files $uri $uri/ /index.php?$query_string;
}
laravel-modules安装
- 首先在 Laravel 项目根目录下使用 Composer 安装该扩展包
composer require nwidart/laravel-modules
- Publish the configuration file by running the following command
php artisan vendor:publish --provider="Nwidart\Modules\LaravelModulesServiceProvider"
- Generate the first module of the application with the following command.
php artisan module:make Admin
4.要让模块目录中定义的类可以自动加载,需要配置根目录下的composer.json
{
"autoload": {
"psr-4": {
"App\\": "app/",
"Modules\\": "Modules/"
}
}
}
- 配置完成后运行以下命令让修改生效
composer dump-autoload
- Execute domain name plus module name(例如:http://test.com/admin)
路由
基础
定义在 routes/api.php 文件中的路由,will be applied automatically /api URI 前缀,可以通过修改 RouteServiceProvider class to modify prefixes and other routing group options.
- 基础路由
Route::get('/greeting', function () {
return 'Hello World';
});
//http://laram.com/api/v1/admin/user
Route::group(['prefix' => 'v1/admin','middleware'=>'admin_api_auth'],function () {
//路径用“\”分割
Route::post('/user', "v1\[email protected]");
});
- Available routing methods
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
- Multiple responses are possibleHTTP请求的路由
Route::match(['get', 'post'], '/', function () {
//
});
Route::any('/', function () {
//
});
路由参数
- 必填参数
Route::get('/user/{id}', function ($id) {
return 'User '.$id;
});
//Define multiple parameters in the route
Route::get('/posts/{post}/comments/{comment}', function ($postId, $commentId) {
//
});
- 可选参数
Route::get('/user/{name?}', function ($name = null) {
return $name;
});
Route::get('/user/{name?}', function ($name = 'John') {
return $name;
});
- 正则表达式约束
Route::get('/user/{name}', function ($name) {
//
})->where('name', '[A-Za-z]+');
Route::get('/user/{id}/{name}', function ($id, $name) {
//
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
//Regular expression pattern tool
Route::get('/user/{id}/{name}', function ($id, $name) {
//
})->whereNumber('id')->whereAlpha('name');
Route::get('/user/{name}', function ($name) {
//
})->whereAlphaNumeric('name');
Route::get('/user/{id}', function ($id) {
//
})->whereUuid('id');
Route::get('/category/{category}', function ($category) {
//
})->whereIn('category', ['movie', 'song', 'painting']);
- 全局约束
// App\Providers\RouteServiceProvider 类的 boot 方法
public function boot()
{
Route::pattern('id', '[0-9]+');
}
命名路由
Route::get('/user/profile', function () {
//
})->name('profile');
Route names should always be unique
路由组
- 路由中间件
Route::middleware(['first', 'second'])->group(function () {
Route::get('/', function () {
// Use the first and second middleware...
});
Route::get('/user/profile', function () {
// Use the first and second middleware...
});
});
- 控制器
use App\Http\Controllers\OrderController;
Route::controller(OrderController::class)->group(function () {
Route::get('/orders/{id}', 'show');
Route::post('/orders', 'store');
});
- 子域路由
Route::domain('{account}.example.com')->group(function () {
Route::get('user/{id}', function ($account, $id) {
//
});
});
- 路由前缀
Route::prefix('admin')->group(function () {
Route::get('/users', function () {
// Matches The "/admin/users" URL
});
});
中间件
1.创建中间件
php artisan make:middleware EnsureTokenIsValid
将在app/Http/Middleware Place a new one in the directory EnsureTokenIsValid 类.HTTP Requests must go through this middleware before reaching the application
The following middleware will be before the application processes the request**执行一些任务:
<?php
namespace App\Http\Middleware;
use Closure;
class EnsureTokenIsValid
{
public function handle($request, Closure $next)
{
// 执行操作
return $next($request);
}
}
This middleware will perform its task after the request is processed by the application:
<?php
namespace App\Http\Middleware;
use Closure;
class AfterMiddleware
{
public function handle($request, Closure $next)
{
$response = $next($request);
// 执行操作
return $response;
}
}
- 注册中间件
在 app/Http/Kernel.php 类的
$middleware ------------------>全局中间件
routeMiddleware ------------>Assign middleware to routes
'admin_api_auth' => \Modules\Admin\Http\Middleware\AdminApiAuth::class,
Route::get('/profile', function () {
//
})->middleware('admin_api_auth');
Route::middleware('admin')->prefix('v1/admin')->group(function () {
Route::post('/user', "v1\[email protected]");
});
//Exclude middleware
Route::withoutMiddleware([EnsureTokenIsValid::class])->group(function () {
Route::get('/profile', function () {
//
});
});
依赖注入和控制器
//构造函数注入
<?php
namespace App\Http\Controllers;
use App\Repositories\UserRepository;
class UserController extends Controller
{
/** * User repository instance. */
protected $users;
/** * 创建一个新的控制器实例. * * @param \App\Repositories\UserRepository $users * @return void */
public function __construct(UserRepository $users)
{
$this->users = $users;
}
}
//方法注入
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
/** * Store a new user. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */
public function store(Request $request)
{
$name = $request->name;
//
}
}
请求
Interact with the request
//Retrieve request path : http://larabbs/api/v1/admin/user
$request->path(): //api/v1/admin/user
//检查请求路径 / 路由
$request->is('api/v1/admin/*'):
$request->routeIs('admin.*'):
//检索请求 URL(完整 URL)
$request->url(): //http://larabbs/api/v1/admin/user
$request->fullUrl():
$request->fullUrlWithQuery(['type' => 'phone']);
//Retrieve the requesting host
$request->host();
$request->httpHost();
$request->schemeAndHttpHost();
//Retrieve request method
$request->method();
$request->isMethod('post');
//请求头
$request->header('X-Header-Name')
$request->header('X-Header-Name', 'default');
$request->hasHeader('X-Header-Name');
//请求 IP 地址
$request->ip();
//请求协商
$request->getAcceptableContentTypes();
//Accepts an array of content types
$request->accepts(['text/html', 'application/json'])
接收数据
//Retrieve all input data
$request->all();
$request->collect();
//Retrieve an input value
$request->input('name');
$request->input('name', 'Sally');
$request->input('products.0.name');
$request->input('products.*.name');
$request->input();
//Retrieve input from query string
$request->query('name');
//Retrieve part of input data
$request->only(['username', 'password']);
$request->only('username', 'password');
$request->except(['credit_card']);
$request->except('credit_card');
//Check if the input value exists
$request->has('name')
$request->has(['name', 'email'])
//存在,并且不为空
$request->filled('name')
//Merge additional inputs
$request->merge(['votes' => 0]);
//The corresponding key does not exist in the requested input data
$request->mergeIfMissing(['votes' => 0]);
旧数据
- Data is persisted between requests
$request->flash();
- Pass a subset of the requested data to Session(Exclude sensitive data like passwords Session 外):
$request->flashOnly(['username', 'email']);
$request->flashExcept('password');
- 获取旧数据
//old 方法会从 Session Retrieve input data that was previously flashed
$request->old('username');
文件
- 获取上传的文件
$file = $request->file('photo');
$file = $request->photo;
$request->hasFile('photo')
//验证成功上传
$request->file('photo')->isValid()
//File path and extension
$path = $request->photo->path();
$extension = $request->photo->extension();
- 存储上传的文件
$path = $request->photo->store('images');
$path = $request->photo->store('images', 's3');
//接受路径、文件名和磁盘名作为其参数
$path = $request->photo->storeAs('images', 'filename.jpg');
$path = $request->photo->storeAs('images', 'filename.jpg', 's3');
响应
- Response 对象
return response()->json($result,400);
- 文件下载
return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);
- 文件响应(The file is displayed in the user's browser)
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
Validation and error handling
- **创建Modules\Admin\Http\Requests\TestRequest **
php artisan modul:make-request TestRequest Admin
- Add validation rules and prompts
<?php
namespace Modules\Admin\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class TestRequest extends FormRequest
{
public function rules()
{
return [
'id'=>'required|is_positive_integer',
];
}
/** * Determine if the user is authorized to make this request. * * @return bool */
public function authorize()
{
return true;
}
public function messages()
{
return ['id.required'=>'id必填','id.is_positive_integer'=>'id需为整数'];
}
}
- 自定义验证规则
在Modules\Admin\ProvidersRouteServiceProvider下
use Validator;
public function boot()
{
parent::boot();
//验证正整数
Validator::extend('is_positive_integer', function($attribute, $value, $parameters, $validator) {
if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
return true;
}else{
return false;
}
});
}
- 异常处理
在App\Exceptions\Handler下
public function render($request, Throwable $exception)
{
if($request->is("api/*")){
// apiExceptions actively thrown by the interface
if($exception instanceof ValidationException){
$result = [
"code"=>404,
"message"=>array_values($exception->errors())[0][0],
];
return response()->json($result,400);
}
else{
$result = [
"code"=>400,
"message"=>$exception->getMessage(),
];
return response()->json($result,400);
}
}
return parent::render($request, $exception);
}
}
边栏推荐
猜你喜欢
phar反序列化
它们不一样!透析【观察者模式】和【发布订阅模式】
Patience sorting - specializing in quickly solving the longest increasing subarray
iNFTnews | 元宇宙为企业发展带来新思路
egg(二十):fs读取本地的txt文件
Kubernetes资源编排系列之四: CRD+Operator篇
Jingdong T9 pure hand type 688 pages of god notes, SSM framework integrates Redis to build efficient Internet applications
GPT3中文自动生成小说「谷歌小发猫写作」
数字图像处理(六)—— 图像压缩
GHOST tool to access the database
随机推荐
NSSCTF部分复现
GHOST tool to access the database
api的封装
【云原生】云原生相关技术概念总结
promise学习笔记
高数_证明_基本初等函数的导数公式
json根据条件存入数据库
Dry goods: design high concurrency architecture from scratch
ggplot2可视化水平箱图并使用fct_reorder排序数据、使用na.rm处理缺失值(reorder boxplot with fct_reorder)、按照箱图的中位数从大到小排序水平箱图
使用 PyGame 的冒泡排序可视化工具
Node简介
ERROR Failed to compile with 1 error
带你玩转“超大杯”ECS特性及实验踩坑【华为云至简致远】
The situation of the solution of the equation system and the correlation transformation of the vector group
Es的索引操作(代码中的基本操作)
spark集群环境搭建
调研阶段复盘
redis设计与实现 笔记(一)
Redis哨兵的配置和原理
Grid 布局介绍