js reduce实现中间件_laravel如何实现中间件?

简介

Laravel 中间件提供了一种方便的机制来过滤进入应用的 HTTP 请求, 如ValidatePostSize用来验证POST请求体大小、ThrottleRequests用于限制请求频率等。

执行原理

首先,入口文件index.php加载了autoload和引导文件bootstrap

require __DIR__.'/../bootstrap/autoload.php';

$app = require_once __DIR__.'/../bootstrap/app.php';

并在引导文件bootstrap/app.php中初始化了Application实例

$app = new Illuminate\Foundation\Application( realpath(__DIR__.'/../'));

我们先跳过如何初始化Application(后面会有简单介绍),再回到入口文件(index.php)中,通过从Application实例$app中获取Http Kernel对象来执行handle方法,换取response。

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle( $request = Illuminate\Http\Request::capture());

$response->send();

$kernel->terminate($request, $response);

换取响应后,把响应内容返回给Client,并执行后续操作(terminate,如关闭session等)。

实例化Application:

在初始化Application(启动容器)时,Laravel主要做了三件事情注册基础绑定

注册基础服务提供者

注册容器核心别名

注册完成以后,我们就能直接从容器中获取需要的对象(如Illuminate\\Contracts\\Http\\Kernel),即使它是一个Interface。获取Illuminate\Contracts\Http\Kernel类时,我们得到的真正实例是 App\Http\Kernel

// bootstrap/app.php

$app->singleton(

Illuminate\Contracts\Http\Kernel::class,

App\Http\Kernel::class

);

Handle

从容器中获得Http Kernel对象后,Laravel通过执行kernel->handle来换取response对象。

//Illuminate\Foundation\Http\Kernel.php

public function handle($request)

{

$request->enableHttpMethodParameterOverride();

$response = $this->sendRequestThroughRouter($request);

//......

}

enableHttpMethodParameterOverride方法开启方法参数覆盖,即可以在POST请求中添加_method参数来伪造HTTP方法(如post中添加_method=DELETE来构造HTTP DELETE请求)。

然后Laravel把请求对象(request)通过管道流操作。

protected function sendRequestThroughRouter($request)

{

return (new Pipeline($this->app))

->send($request)

->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)

->then($this->dispatchToRouter());

}

/**

* Get the route dispatcher callback.

*

* @return \Closure

*/

protected function dispatchToRouter()

{

return function ($request) {

$this->app->instance('request', $request);

return $this->router->dispatch($request);

};

}

Pipeline是laravel的管道操作类。在这个方法中,发送一个$request对象通过middleware中间件数组,最后在执行dispatchToRouter方法。注意,这里的中间件只是全局中间件。即首先让Request通过全局中间件,然后在路由转发中($this->dispatchToRouter()),再通过路由中间件及中间件group。

所以,到这里为止,Laravel的请求交给了Pipeline管理,让我们来看看这个Pipeline究竟是怎样处理的。

///Illuminate\Pipeline\Pipeline.php

public function then(Closure $destination)

{

$pipeline = array_reduce(

array_reverse($this->pipes), $this->carry(), $this->prepareDestination($destination)

);

return $pipeline($this->passable);

}

protected function prepareDestination(Closure $destination)

{

return function ($passable) use ($destination) {

return $destination($passable);

};

}

protected function carry()

{

return function ($stack, $pipe) {

return function ($passable) use ($stack, $pipe) {

if ($pipe instanceof Closure) {

return $pipe($passable, $stack);

} elseif (! is_object($pipe)) {

list($name, $parameters) = $this->parsePipeString($pipe);

$pipe = $this->getContainer()->make($name);

$parameters = array_merge([$passable, $stack], $parameters);

} else {

$parameters = [$passable, $stack];

}

return $pipe->{$this->method}(...$parameters);

};

};

}

我们来看看最重要的then方法, 在这方法中$destination表示通过该管道最后要执行的Closure(即上述的dispatchToRouter方法)。passable表示被通过管道的对象Request。

php内置方法array_reduce把所有要通过的中间件($this->pipes)都通过carry方法($this->pipes不为空时)并压缩为一个Closure。最后在执行prepareDestination。array_reduce($pipes, callback($stack, $pipe), $destination), 当pipes为空时,直接执行destination,否则将所有$pipes压缩为一个Closure,最后在执行destination。

列如我有两个中间件

Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

App\Http\Middleware\AllowOrigin::class,//自定义中间件

将这两个中间件通过array_reduce方法时,返回压缩后的Closure如:

该Closure共有三个层, 前面两个为两个中间件,后面个位最后要执行的Closure(即上述的dispatchToRouter方法)。

//中间件handlepublic function handle($request, Closure $next){}

在第一个通过的中间件(此处是CheckForMaintenanceMode)handle方法中,dump($next)如下

在第二个通过的中间件(共两个,此处是AllowOrigin)handle方法中,dump($next)如下

由此可知,中间件在执行$next($request)时,表示该中间件已正常通过,并期待继续执行下一个中间件。直到所有中间件都执行完毕,最后在执行最后的destination(即上述的dispatchToRouter方法)

以上是Laravel在通过全局中间件时的大致流程,通过中间件group和路由中间件也是一样的, 都是采用管道流操作,详情可翻阅源码Illuminate\Routing\Router->runRouteWithinStack

本书做了一个很好的归纳。同时也欢迎点击,正在跳转加入,任何问题可以一起讨论,也欢迎大家一起踊跃发言!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值