So I have been reading up on the command lifecycle methods beforeExecute and afterExecute and have created a simple command (see below - cut down version of my command code - very simple). However, the before and after methods are never executed?
All I get as the output is execute. Am I missing something here? The docs don’t suggest I need to do anything special, and that these methods should be executed in a similar manner to other lifecycle methods on Table and Controller classes…
class LifecycleCommand extends Command
{
public function execute(Arguments $args, ConsoleIo $io)
{
$io->out('Execute');
}
public function beforeExecute(EventInterface $event, Arguments $args, ConsoleIo $io): void
{
parent::beforeExecute($event, $args, $io);
$io->out('before');
}
public function afterExecute(EventInterface $event, Arguments $args, ConsoleIo $io, ?int $result): void
{
parent::afterExecute($event, $args, $io, $result);
$io->out('after');
}
}
those methods are hooked up via the event system from cakephp, so if your command is not hooked up to the events manager, then it won’t automatically attach those methods.
I will adjust the docs accordingly but you can do this instead for now in your src/Application.php
public function events(EventManagerInterface $eventManager): EventManagerInterface
{
$eventManager->on(new LiveCycleCommand());
return $eventManager;
}
Hmm, I am still having a bit of issue as the command also uses dependency injection - and now this line complains about the injected service not been passed as an argument.
$eventManager->on(new LiveCycleCommand());
I’ll see if I can figure it out and post an update here if I do.
For added context, I want to lock the command in the beforeExecute, and release the lock in the afterExecute method, using the DI service to handle the locking (in Redis).
Not quite working as I expected, as ALL commands now hook into the before and after execute methods defined LiveCycleCommand::class - which I guess makes sense as they are general Command events.
I’ll have a think about a better approach - but thanks for your advice.