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:
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...
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).
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).
You can use the following to dispatch a command.
app('Illuminate\Bus\Dispatcher')->dispatch(new EmailPersonCommand('email@you.com', $otherdata));
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()
.
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.