Laravel 6.0 将新增为指定队列任务设置中间件的功能


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

class SomeMiddleware
{
    public function handle($command, $next)
    {
        // Do something...

        return $next($command);
    }
}

此外,还可以在分发任务时动态指定中间件,这些中间件会自动和定义在该任务类的 middleware() 方法返回的中间件合并:

SomeJob::dispatch()->through([new SomeMiddleware]);

该特性将会在本月底发布的 Laravel 6 中提供,你可以在这个 Pull Request 中查看更多细节。


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Laravel 6 之后新版本的发布周期介绍

>> 下一篇: Laravel 5.8 新特性系列 —— 编译后的 Blade 模板引入编译前模板文件路径以便调试