Command beforeExecute and afterExecute lifecycle methods

Hello,

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…:thinking:

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;
    }

Thanks,

I have also since found this in the manual: Events System | CakePHP

yup, that is the more generic way of listening to all command events via the eventmanager.

But you are absolutely right and command hooks should automatically be usable when someone overwrites that method.

I have created a PR which adds this functionality. add command instances to the event manager by default by LordSimal · Pull Request #19540 · cakephp/cakephp · GitHub

If the other core devs agree this will automatically be fixed in CakePHP 5.4

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).

Then you need

        $command = $this->getContainer()->get(LiveCycleCommand::class);
        $eventManager->on($command);
1 Like

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.