Laravel
Jobs
Every action that takes some time to process should be sent to the background and queued. Making a user wait for an action while they stare at a long loading screen is not a good user experience.
Some examples:
- Sending any communications to a client
- Connecting to third-party services and processing the data
- Imports & Exports of big datasets
- ...and many more
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 it does, 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 responsibility. If creating a new user means sending them an email, sending an SMS and shipping them a membership card, those should be three separate jobs. Chain the jobs if they rely on each other — Laravel makes this a simple task. See the Single Responsibility Principle.
You can find more details in this excellent 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 dispatching on your job class is a neat and clean way to write your code, and lately we have not had issues with static analyzers:
// GOOD
use Illuminate\Support\Facades\Bus;
Bus::dispatch(new YourJob($parameter));
// also GOOD (Preferred)
YourJob::dispatch($parameter);
