Laravel5.1框架注册中间件的三种场景详解

本文实例讲述了Laravel5.1框架注册中间件的三种场景。分享给大家供大家参考,具体如下:

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

  • 1、在控制器中的方法中注册中间件

这种需求是最为常见,这个例子是给IndexController中的index方法添加中间件。

Route::get('/', ['middleware'=>['App\Http\Middleware\EmailMiddleware'],'uses'=>'IndexController@index']);

  • 2、在整个控制器中注册中间件

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

控制器基类(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.");
  }


      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/5660.html