Taylor Otwell 在 Laravel 6 中新增了为指定队列任务设置中间件的能力,以便我们在执行某些队列任务之前先执行一些业务逻辑:
This [pull request] adds an easy way to have job specific middleware for queued jobs. Global job middleware were actually already possible by calling Bus::pipeThrough([]) in a service provider during the application boot process…These middleware provide a convenient location to wrap jobs in some logic before they are executed.
我们可以在 Job 类中定义middleware()
方法来设置对应的中间件,该方法返回的是中间件对象实例数组,因此可以定义多个中间件:
public function middleware()
{
return [new SomeMiddleware];
}
下面是中间件的示例代码,与之前的中间件定义并无大的区别,只是将request 参数替换成了command :
代码语言:javascript复制class SomeMiddleware
{
public function handle($command, $next)
{
// Do something...
return $next($command);
}
}
此外,还可以在分发任务时动态指定中间件,这些中间件会自动和定义在该任务类的middleware()
方法返回的中间件合并:
SomeJob::dispatch()- through([new SomeMiddleware]);
该特性将会在本月底发布的Laravel 6 中提供,你可以在这个Pull Request 中查看更多细节。