@@ -570,10 +570,54 @@ Lifecycle Callbacks
570570Like Controllers, Commands offer lifecycle events that allow you to observe
571571the framework calling your application code. Commands have:
572572
573- - ``Command.beforeExecute `` Is called before a command's ``execute() `` method
574- is. The event is passed the ``ConsoleArguments `` parameter as ``args ``. This
575- event cannot be stopped or have its result replaced.
576- - ``Command.afterExecute `` Is called after a command's ``execute() `` method is
577- complete. The event contains ``ConsoleArguments `` as ``args `` and the command
578- result as ``result ``. This event cannot be stopped or have its result
579- replaced.
573+ - ``Command.beforeExecute `` is called before a command's ``execute() `` method.
574+ The event is passed the ``Arguments `` parameter as ``args `` and the
575+ ``ConsoleIo `` parameter as ``io ``. This event cannot be stopped or have its
576+ result replaced.
577+ - ``Command.afterExecute `` is called after a command's ``execute() `` method is
578+ complete. The event contains ``Arguments `` as ``args ``, ``ConsoleIo `` as
579+ ``io `` and the command result as ``result ``. This event cannot be stopped or
580+ have its result replaced.
581+
582+ .. versionadded :: 5.3.0
583+ The ``beforeExecute() `` and ``afterExecute() `` hook methods were added.
584+
585+ beforeExecute()
586+ ---------------
587+
588+ .. php :method :: beforeExecute(EventInterface $event, Arguments $args, ConsoleIo $io)
589+
590+ Called before the ``execute() `` method runs. Useful for initialization and
591+ validation::
592+
593+ use Cake\Event\EventInterface;
594+
595+ class MyCommand extends Command
596+ {
597+ public function beforeExecute(EventInterface $event, Arguments $args, ConsoleIo $io): void
598+ {
599+ parent::beforeExecute($event);
600+
601+ $io->out('Starting command execution');
602+
603+ if (!$this->checkPrerequisites()) {
604+ $io->abort('Prerequisites not met');
605+ }
606+ }
607+ }
608+
609+ afterExecute()
610+ --------------
611+
612+ .. php :method :: afterExecute(EventInterface $event, Arguments $args, ConsoleIo $io)
613+
614+ Called after the ``execute() `` method completes. Useful for cleanup and
615+ logging::
616+
617+ public function afterExecute(EventInterface $event, Arguments $args, ConsoleIo $io, mixed $result): void
618+ {
619+ parent::afterExecute($event);
620+
621+ $this->cleanup();
622+ $io->out('Command execution completed');
623+ }
0 commit comments