本文实例讲述了Laravel5.1框架注册中间件的三种场景。分享给大家供大家参考,具体如下:
在Laravel中注册中间件主要有三种场景,一种给控制器中的方法进行注册,一种是给整个控制器进行注册,最后一种是给全局注册中间件。
这种需求是最为常见,这个例子是给IndexController中的index方法添加中间件。
Route::get('/', ['middleware'=>['App\Http\Middleware\EmailMiddleware'],'uses'=>'IndexController@index']);
这种需求有的时候也会出现,如果给整个控制器中注册中间件,那么这个控制器中的所有方法都注册了该中间件。跟我一起来找到答案!
控制器基类(Controller.php)
首先来看一下控制器基类,可以看到Controller类继承了BaseController类,而BaseController的路径是Illuminate\Routing\Controller,然后我们来看看Laravel的源码。
<?php namespace App\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; abstract class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; }
BaseController类
从源码中我们可以看到有一个属性为middleware,这个middleware属性就是我们要找的,所以只要在需要注册的控制器下使用这个属性即可完成注册。
protected $middleware = [];
<?php namespace Illuminate\Routing; use BadMethodCallException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; abstract class Controller { /** * The middleware registered on the controller. * * @var array */ protected $middleware = []; /** * Register middleware on the controller. * * @param array|string|\Closure $middleware * @param array $options * @return \Illuminate\Routing\ControllerMiddlewareOptions */ public function middleware($middleware, array $options = []) { foreach ((array) $middleware as $m) { $this->middleware[] = [ 'middleware' => $m, 'options' => &$options, ]; } return new ControllerMiddlewareOptions($options); } /** * Get the middleware assigned to the controller. * * @return array */ public function getMiddleware() { return $this->middleware; } /** * Execute an action on the controller. * * @param string $method * @param array $parameters * @return \Symfony\Component\HttpFoundation\Response */ public function callAction($method, $parameters) { return call_user_func_array([$this, $method], $parameters); } /** * Handle calls to missing methods on the controller. * * @param array $parameters * @return mixed * * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException */ public function missingMethod($parameters = []) { throw new NotFoundHttpException('Controller method not found.'); } /** * Handle calls to missing methods on the controller. * * @param string $method * @param array $parameters * @return mixed * * @throws \BadMethodCallException */ public function __call($method, $parameters) { throw new BadMethodCallException("Method [{$method}] does not exist."); }
给整个控制器注册中间件
我们选用系统的Authenticate中间件来举例,这个中间件是用于检测用户是否登录。
注意:中间件的名称为键,值可以是一个空数组
protected $middleware = ['\App\Http\Middleware\Authenticate'=>[]];
- 3、全局注册中间件
打开app/Http/Kernel.php,这是一个内核文件,可以看到一个属性$middleware,我们只需要将我们自定义的中间件的路径添加到这个$middleware 这个属性中即可。
此外还有一个$routeMiddleware属性,使用这个属性可以根据路由来注册中间件。
我们的路由有:goods/info,goods/detail两个路由器
我们可以将$routeMiddleware属性添加一行
'goods.*' => \App\Http\Middleware\GoodsMiddleware::class,
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * @var array */ protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ]; /** * The application's route middleware. * * @var array */ protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, ]; }
扫码二维码 获取免费视频学习资料
- 本文固定链接: http://phpxs.com/post/6747/
- 转载请注明:转载必须在正文中标注并保留原文链接
- 扫码: 扫上方二维码获取免费视频资料