|
| 1 | +Command Lifecycle Events |
| 2 | +######################## |
| 3 | + |
| 4 | +.. php:namespace:: Cake\Console |
| 5 | +
|
| 6 | +CakePHP commands trigger events during execution that allow you to hook into |
| 7 | +different stages of the command lifecycle. These events work similarly to |
| 8 | +controller lifecycle callbacks. |
| 9 | + |
| 10 | +Event List |
| 11 | +========== |
| 12 | + |
| 13 | +The following events are triggered during command execution: |
| 14 | + |
| 15 | +* ``Command.beforeExecute`` - Before the ``execute()`` method |
| 16 | +* ``Command.afterExecute`` - After the ``execute()`` method completes |
| 17 | + |
| 18 | +Lifecycle Callback Methods |
| 19 | +========================== |
| 20 | + |
| 21 | +beforeExecute() |
| 22 | +--------------- |
| 23 | + |
| 24 | +.. php:method:: beforeExecute(EventInterface $event) |
| 25 | +
|
| 26 | +Called before the ``execute()`` method runs. Useful for initialization and |
| 27 | +validation:: |
| 28 | + |
| 29 | + use Cake\Event\EventInterface; |
| 30 | + |
| 31 | + class MyCommand extends Command |
| 32 | + { |
| 33 | + public function beforeExecute(EventInterface $event): void |
| 34 | + { |
| 35 | + parent::beforeExecute($event); |
| 36 | + |
| 37 | + $this->log('Starting command execution'); |
| 38 | + |
| 39 | + if (!$this->checkPrerequisites()) { |
| 40 | + $event->stopPropagation(); |
| 41 | + $this->io()->error('Prerequisites not met'); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | +afterExecute() |
| 47 | +-------------- |
| 48 | + |
| 49 | +.. php:method:: afterExecute(EventInterface $event) |
| 50 | +
|
| 51 | +Called after the ``execute()`` method completes. Useful for cleanup and |
| 52 | +logging:: |
| 53 | + |
| 54 | + public function afterExecute(EventInterface $event): void |
| 55 | + { |
| 56 | + parent::afterExecute($event); |
| 57 | + |
| 58 | + $this->cleanup(); |
| 59 | + $this->log('Command execution completed'); |
| 60 | + } |
| 61 | + |
| 62 | +Stopping Command Execution |
| 63 | +========================== |
| 64 | + |
| 65 | +You can prevent the ``execute()`` method from running by stopping event |
| 66 | +propagation in ``beforeExecute()``:: |
| 67 | + |
| 68 | + public function beforeExecute(EventInterface $event): void |
| 69 | + { |
| 70 | + if (!$this->isValid()) { |
| 71 | + $event->stopPropagation(); |
| 72 | + $event->setResult(static::CODE_ERROR); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | +When propagation is stopped, ``execute()`` won't run but ``afterExecute()`` |
| 77 | +will still be called for cleanup. |
| 78 | + |
| 79 | +.. note:: |
| 80 | + |
| 81 | + Remember to call ``parent::beforeExecute($event)`` and |
| 82 | + ``parent::afterExecute($event)`` when overriding these methods. |
0 commit comments