Jobs
Every single action that will take some time to process will need to be sent to the background & queued. When a user have a wait for an action and they must look at long loading screens isn’t very good UI experience.
Some of these are for instance:
- Sending any communications to a client
- Connecting to 3rd party services and processing the data
- Imports & Exports of big datasets
- There are many more examples...
There are few characteristics, our Jobs should follow:
- Reentrancy. If a task is interrupted, it can be restarted and completed successfully.
- Idempotence. A task can be called multiple times, without changing the side effects.
- Concurrence. More than one of a task can be run at the same time.
- Sequence Independence. The order of the tasks doesn’t matter, if they do then you should use job chaining.
- Minimal Params. You should not pass full models and services to the jobs as this will make the job classes in the queue very big. Only pass the bare minimum data that you will need. For instance instead of passing the User object just pass in the user ID and do the query when the jobs run to get the details of the user if you need it.
- Single Responsibility. A Job should have a single responsability. When you create a new user send them a email, sms and ship them a membership card, those should be 3 seperate Jobs. Chain the jobs if they are relaint on each other, Laravel makes this a simple task. Single Responsability Principle
You can find more details on awesome talk: Matt Stauffer - Patterns That Pay Off
Dispatching
You SHOULD use Bus::dispatch() Facade or use \Illuminate\Contracts\Bus\Dispatcher DI instead of YourJobClass::dispatch() magic to make code readable for static analyzers but dispatch on your job class if a neat and clean way to write your code and lately we do not have issues with static analyzers:
PHP
// GOOD
use Illuminate\Support\Facades\Bus;
Bus::dispatch(new YouJob($parameter));
// also GOOD (Preferred)
YouJob::dispatch($parameter)
