应用场景:检测登陆,控制器加载数据,传递常量
命令
//中间件创建命令 php artisan make:middleware Check
注意:
1.需要注册中间件
2.中间件命名不能重复
middleware/Check.php代码
<?php namespace AppHttpMiddleware; use Closure; class Check { /** * Handle an incoming request. * * @param IlluminateHttpRequest $request * @param Closure $next * @return mixed */ public function handle($request, Closure $next) { echo 'middleware-check'; return $next($request); } }
注册中间件appHttpKernel.php
routeMiddleware注册
protected $routeMiddleware = [ /* * 注册中间件 * Author:MR.zhou * */ 'check' =>MiddlewareCheck::class, 'goods' =>MiddlewareGoods::class, ];
middlewareGroups注册
protected $middlewareGroups = [ 'web' => [ AppHttpMiddlewareEncryptCookies::class, IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class, IlluminateSessionMiddlewareStartSession::class, // IlluminateSessionMiddlewareAuthenticateSession::class, IlluminateViewMiddlewareShareErrorsFromSession::class, AppHttpMiddlewareVerifyCsrfToken::class, IlluminateRoutingMiddlewareSubstituteBindings::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], // 正常 'dds' =>[ 'goods', 'check' ], /* * 错误示范 * 命名重复: check与routeMiddleware下的check命名重复,路由调用的时候会出错。 * */ 'check' =>[ 'goods', 'check' ]
路由调用
// 中间件群组 (b.验证登陆) Route::group(['middleware' => ['check']], function () { Route::get('/show','IndexController@show'); });
// 可以调用goods、check两个中间件 Route::group(['middleware' => ['dds']], function () { Route::get('/show','IndexController@show'); });
Route::get('admin/profile', function () { // })->middleware('auth'); Route::get('/', function () { // })->middleware('first', 'second');
场景一:加载常量
MiddlewareConstant.php
<?php namespace AppHttpMiddleware; use Closure; class Check { /** * Handle an incoming request. * * @param IlluminateHttpRequest $request * @param Closure $next * @return mixed */ public function handle($request, Closure $next) { define('VERSION','5.8'); return $next($request); } }
Kernel.php注册常量
protected $routeMiddleware = [ 'auth' => AppHttpMiddlewareAuthenticate::class, 'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class, 'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class, 'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class, 'can' => IlluminateAuthMiddlewareAuthorize::class, 'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class, 'signed' => IlluminateRoutingMiddlewareValidateSignature::class, 'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class, 'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class, 'check'=>MiddlewareCheck::class // 注册常量 ];
路由调用:
public function index(){ echo VERSION; }
页面输出:123456
场景二:检测登陆;方法跟上面基本一样
需要掌握的技巧:基本路由加载中间件,加载多个中间件,群组中间件