Subscribe to an event
Register listeners inboot() through the event mapper:
src/Plugin.php
Write a listener
A listener is an invokable class. It’s resolved from the container, so it can depend on any service:src/Listeners/PushContact.php
Priorities
Priority::HIGH (100) runs before Priority::NORMAL (50), which runs before Priority::LOW (0).
Inheritance matters
Listeners match withinstanceof, so a listener on a parent class also receives its subclasses.
Events you can subscribe to
Class names are under
<Module>\Domain\Events\. See the event catalog for the full list, including who listens in core.
Dispatch your own events
Scheduled work
Since v5.2, recurring work is a scheduled task, and slow work is a queued job. Cron runs both, and a background worker, if there is one, picks jobs up sooner. See Background jobs and cron for how they run.Scheduled tasks
ImplementCron\Domain\ScheduledTaskInterface and register the task in boot() under a name that starts with your plugin’s:
src/Plugin.php
src/SyncContacts.php
- The schedule is a cron expression in UTC. A run that was missed happens once on the next cron run.
- Each task runs on its own. One that throws is recorded as failed, with its error, on Settings → System → Queue, and the others still run.
- The label is a closure, so it is translated when shown. Without one, the name is shown.
Queued jobs
Slow work, or work per record, belongs in a job. A job is a small message handled like a command:src/SyncContactsJob.php
toArray()returns plain values. Jobs are stored as JSON; keep ids, not entities.- The handler reloads what it needs, and returns quietly when a record is gone.
- Jobs run at least once. A second run must do no harm.
- A failing job is retried after each
backoffdelay, then kept as a failed job that administrators can retry. - Dispatching from a request is safe:
QueueBusholds the job until the request’s changes are saved.
$this->queue->dispatch(new SyncContactsJob($lastId)), instead of keeping a cursor in an option.
The cron event
Cron\Domain\Events\CronEvent is still dispatched every minute, by the Run plugin cron listeners task, so existing listeners keep working:
Entity changes made in tasks, jobs and cron listeners are flushed when they finish, the same as in a web request.
Testing
- Run the cron tick by hand with
php cron.php, or only the due tasks withphp bin/console app:schedule:run. - Work queued jobs and watch them with
php bin/console app:queue:work --stop-when-empty -vv. - Trigger domain events by doing the thing in the UI, such as creating a user.
- Watch
var/log/app-*.log, and log at the start and end of your listener while developing.