Laravel如何在执行前后调用作业class的方法

Laravel how to call a method of the job class before and after execution

我在使用 laravel 队列时遇到问题。由于我正在使用扩展架构,所以我所做的大部分事情都是使用队列和作业来实现的。例如,在处理大文件时,文件中每 1000 行创建一个作业,并将结果保存到输出文件中。

我有一个 "Process" class,我目前正在将其用作作业的 parent。进程 class 具有 start() 和 end() 方法,在调用作业 handle() 方法后和执行该方法后应调用这些方法。目前的解决方案是从 handle 方法中调用这些方法,但问题是这种方法在作业 class 本身增加了不必要的代码,需要实现者记住调用这些方法。

public function handle()
{
    $this->start(); // <- implementer has to remember to call this

    // Do the actual handle functionality

    $this->end(); // <- and this
}

所以我想知道是否有一种 "clean" 方法不需要从作业 (child) class 调用 parent 方法? 我尝试在作业中使用 queue events but the job class cannot be constructed from the given event object. Dispatching an event 并没有真正帮助,因为您仍然必须在每个作业 classes 中添加这两行额外的内容。

在 laravel 特定实现之外,我还研究了神奇的 __call() 方法,但这只有在 "handle" 方法不存在的情况下才有效,这是'考虑到 artisan make:job 命令默认生成方法(再次要求实现者足够精明才能删除它),这并不是最佳选择。

要明确这一点,当前的解决方案确实有效,但似乎有一种代码味道,即为每个 class.

重复相同的行

您可以创建一个具有句柄函数的父项 class,他将在具有您的逻辑的子项中调用一个受保护的函数,例如:

class MyJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected function start() {
        // your start logic
    }

    protected function stop() {
        // your stop logic
    }

    protected function process() {
        // will be overrittten
    }

    public function handle() {
        $this->start();
        $this->process();
        $this->stop();
    }
}

并且您所有的工作都会延长您的 class,例如:

class SpecificJob extends MyJob
{
    protected function process() {
         // logic
    }
}

查看文档 here 了解完成后调​​用的函数。我敢肯定,如果您仔细研究,就会找到放置 BEFORE 方法的位置。