• 在Laravel中注册中间件


    在Laravel中注册中间件主要有三种场景,一种给控制器中的方法进行注册,一种是给整个控制器进行注册,最后一种是给全局注册中间件。

    1、在控制器中的方法中注册中间件
    这种需求是最为常见,这个例子是给IndexController中的index方法添加中间件。
    

    Route::get('/', ['middleware'=>['AppHttpMiddlewareEmailMiddleware'],'uses'=>'IndexController@index']);

    2、在整个控制器中注册中间件
    这种需求有的时候也会出现,如果给整个控制器中注册中间件,那么这个控制器中的所有方法都注册了该中间件。跟我一起来找到答案!
    

    控制器基类(Controller.PHP)

    首先来看一下控制器基类,可以看到Controller类继承了BaseController类,而BaseController的路径是IlluminateRoutingController,然后我们来看看Laravel的源码。

    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 SymfonyComponentHttpFoundationResponse */ 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 SymfonyComponentHttpKernelExceptionNotFoundHttpException */ 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 = ['AppHttpMiddlewareAuthenticate'=>[]]; 1 1 3、全局注册中间件 打开app/Http/Kernel.php,这是一个内核文件,可以看到一个属性$middleware,我们只需要将我们自定义的中间件的路径添加到这个$middleware 这个属性中即可。 此外还有一个$routeMiddleware属性,使用这个属性可以根据路由来注册中间件。 我们的路由有:goods/info,goods/detail两个路由器 我们可以将$routeMiddleware属性添加一行 'goods.*' => AppHttpMiddlewareGoodsMiddleware::class, 1 1 AppHttpMiddlewareAuthenticate::class, 'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class, 'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class, ]; }
  • 相关阅读:
    WPF 快捷键读写txt
    win10 UWP GET Post
    win10 UWP GET Post
    win10 UWP Hmac
    win10 UWP Hmac
    win10 UWP MessageDialog 和 ContentDialog
    MySQL 触发器-更新字段时,status列会加一
    [SDOI2018]旧试题
    win10 UWP MessageDialog 和 ContentDialog
    win10 UWP RSS阅读器
  • 原文地址:https://www.cnblogs.com/shamojituan/p/6656579.html
Copyright © 2020-2023  润新知