在 laravel 框架中,Illuminate\Pipeline\Pipeline
类是实现 laravel 中间件功能的重要工具之一。他的作用是,将一系列有序可执行的任务依次执行。也有人把这种功能成为管道模式,比如下面这篇文章的介绍:
Laravel 中管道设计模式的使用 —— 中间件实现原理探究
今天我们就来探究一下 Pipeline 类的功能和源码。
Pipeline 的使用
Pipeline(管道)顾名思义,就是将一系列任务按一定顺序在管道里面依次执行。其中任务可以是匿名函数,也可以是拥有特定方法的类或对象。
我看先来看一段 Pipeline 的使用代码,了解一下Pipeline 具体是如何使用的。
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Pipeline\Pipeline;
class Test extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'test';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$task1 = function($passable, $next){
$this->info('这是任务1');
$this->info('任务1的参数 '.$passable);
return $next($passable);
};
$task2 = function($passable, $next){
$this->info('这是任务2');
$this->info('任务2的参数 '.$passable);
return $next($passable);
};
$task3 = function($passable, $next){
$this->info('这是任务3');
$this->info('任务3的参数 '.$passable);
return $next($passable);
};
$pipeline = new Pipeline();
$rel = $pipeline->send('任务参数')
->through([$task1, $task2, $task3])
->then(function(){
$this->info('then 方法');
return 'then 方法的返回值';
});
$this->info($rel);
}
}
运行上面代码,我们得到如下结果
这是任务1