Laravel 5: 路由前后的中间件

Laravel 5: Middleware before & after into routes

我有两个中间件:beforeCache 和 afterCache,都在内核上注册了。

我想按以下顺序将它们调用到路由中: 1.缓存前 2.我的控制器 3.缓存后

如果我这样定义路由:

Route::get('especies/{id}', [
    'middleware' => 'beforeCache', 
    'uses' => 'MyController@myMethod', 
    'middleware' => 'afterCache', 
]);

beforeCache 不执行,因为 afterCache 正在重新定义相同的数组键中间件。

我应该怎么做?谢谢!

我假设您在此使用 5.1,但您所做的实际上是尝试在路线上定义一组属性。方括号 [] 只是 array(...).

的 shorthand 版本

根据文档 (http://laravel.com/docs/5.1/middleware#defining-middleware),特别是中间件之前/之后,您只需要 return 某种方式。

对于 Before middlewares,你执行你的代码,return你的代码执行后的下一个请求。

public function handle($request, Closure $next)
{
    // Perform action

    return $next($request);
}

对于 After 中间件,您处理请求的其余部分,然后执行您的代码,最后 return 响应。

public function handle($request, Closure $next)
{
    $response = $next($request);
    // Perform action
    return $response;
}

路线最终看起来像这样,

Route::get('especies/{id}',[
    'middleware' => [
        'beforeCache',
        'afterCache'
    ],
    'uses' => 'MyController@myMethod'
]);
class BeforeMiddleware implements Middleware {

    public function handle($request, Closure $next)
    {
        // Do Stuff
        return $next($request);
    }

}

class AfterMiddleware implements Middleware {

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        // Do stuff
        return $response;
    }

}

1-before中间件运行然后传递请求。

2-after中间件让请求得到处理,然后对其进行操作