简体   繁体   中英

Laravel Job - best way to execute a command at start and at fail of every job

I have a piece of code that takes the user (passed into the job constructor) and notifies the user via a websocket to the job status.

It is effectively one line that needs to be added to the start of the handle method (before the job starts), one to the end of the handle method (after the jobs has completed) and then on in the fail method.

Other than adding this to each job manually, what is the best way to do this? Something like a trait, middleware etc. but I don't think either of these will work.

One way could be extending the job/command class like:

class MyJob extends Job {
    public function handle() {
    try {
        do_stuff_at_start();
        $this->process();
    } catch (Exception $e) {
        do_stuff_when_fails();
    }
    abstract public function process();
}

and all Your jobs could implement process() method that is responsible for handling logic. Just a loose idea - not sure if it fits Your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM