Laravel如何知道在处理请求后是否应该运行中间件? [英] How does Laravel know whether a middleware should be run after the request handled?

查看:88
本文介绍了Laravel如何知道在处理请求后是否应该运行中间件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了源代码,只有一个管道将所有中间件读取为数组.这些中间件应该在请求 dispatchToRouter.

I read the source code, and there is only a pipeline which reads all middlewares as an array. These middlewares should be run before the request dispatchToRouter.

return (new Pipeline($this->app))
    ->send($request)
    ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
    ->then($this->dispatchToRouter()); 

但是,如果我创建了中间件,则应该在处理请求之后运行中间件.在这里以及何时在laravel源代码中执行中间件?

However, if I created an after-middleware, the after-middleware should be run after the request handled. here and when the after-middleware being execute in the laravel source code?

推荐答案

根据laravel官方文档,

According to laravel official documentation,

在请求之前或之后运行中间件取决于中间件本身.

Whether a middleware runs before or after a request depends on the middleware itself.

因此,基本上,它取决于中间件的句柄功能.通常,我们在处理请求之前就执行中间件:

So, basically it depends on the handle function of the middleware. Normally we execute middleware just before handling the request like this:

public function handle($request, Closure $next)
{
    // Perform some operation for Ex. checking user role

    return $next($request);
}

在上面的函数中,我们在发送执行操作请求之前执行了一些操作.

In above function, we execute some operation before sending request to perform operation.

在另一种情况下,中间件将在应用程序处理请求后执行其任务,如下所示:

In the another case, middleware would perform its task after the request is handled by the application like this:

public function handle($request, Closure $next)
{
    $response = $next($request);

    // Perform some operation after the request is handled by the application

    return $response; /* finally, response is returned */
}

总而言之,在中间件之前,我们首先执行一些操作,然后将请求发送到应用程序以获取响应,并将其返回给客户端.在中间件之后,我们首先将请求发送到应用程序以获取响应,然后执行操作,最后将响应从中间件返回到客户端.

In summary, In before middleware, we perform some operations at first and then send request to the application to get response which is returned to client end. In after middlware, we send request to the application at first to get response then we perform our actions and finally we return the response from middleware to client end.

您可以看到官方文档: https://laravel.com/docs/5.8/middleware#defining-middleware

You can see official docs: https://laravel.com/docs/5.8/middleware#defining-middleware

这篇关于Laravel如何知道在处理请求后是否应该运行中间件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆