Laravel commands and jobs

前端 未结 3 1137
死守一世寂寞
死守一世寂寞 2021-01-30 17:35

I was wondering what the difference is between the different command-like classes in Laravel 5.1. As far as I can tell Laravel 5.1 has the following available:

  • Con
3条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 18:03

    Console Commands

    Laravel has had console "commands" for some time. They are basically unchanged, and work as they always have. In simple terms, they are the equivalent of routes for the command line - the entry point into the application. They are in no way related to...

    The Command Bus

    Laravel 5.0 introduced an implementation of the Command Bus pattern - Command Bus Commands. (I believe these were renamed to Jobs because of the resulting confusion between them and CLI Commands).

    A command bus as two parts - an object that represents a command to be executed, with any and all data it needs (the job), and a class to execute the command (the handler).

    The Handler

    In laravel, you can declare a job to be self handling - that is, it has a handle method itself.

    If you want to register a command handler, you can call the following in a service provider:

    app('Illuminate\Bus\Dispatcher')->maps(['Job' => 'Handler']);
    

    where Job is the class name for the job, and Handler is the class name for the handler.

    The handlers directory in laravel 5.0 was a way of implicitly declaring those relationships (ie. EmailCommand in the commands folder would have an EmailCommandHandler in the handlers folder).

    Dispatching a Command

    You can use the following to dispatch a command.

    app('Illuminate\Bus\Dispatcher')->dispatch(new EmailPersonCommand('email@you.com', $otherdata));
    

    Queues

    Jobs, by default, will run as soon as they are called (or dispatched). Setting them as ShouldQueue will always pass them to a queue when they are dispatched.

    If you want to run them synchronously sometimes, and asynchronously other times, you can call $dispatcher->dispatchToQueue($job) when you want them to be queued. This is all that happens internally when you pass a ShouldQueue job to ->dispatch().

    edit: To Queuing (or not)

    I've just had a longer look at the dispatcher. The dispatch method checks if the command is a ShouldQueue, and either forwards it to dispatchToQueue or dispatchNow. You can call either of those methods directly instead of dispatch with your command should you wish to override the default behaviour.

    So in your case, depending on what the "default" behaviour of your job is (ie. will it normally be queued?) either: - have it ShouldQueue, and use dispatchNow in the CLI Command. - don't have it ShouldQueue, and use dispatchToQueue where you call it in your code.

    From the sounds of it, i'd do the former.

提交回复
热议问题