0

In CakPHP 3.6.0 Console Commands have been added to replace Shells and Tasks long term.

I'm currently designing a cronjob command to execute other commands in different time intervals. So I want to run a command from a Command class like this:

namespace App\Command;
// ...

class CronjobCommand extends Command
{
    public function execute(Arguments $args, ConsoleIo $io)
    {
        // Run other command
    }
}

For Shells / Tasks it is possible to use Cake\Console\ShellDispatcher:

$shell = new ShellDispatcher();
$output = $shell->run(['cake', $task]);

but this does not work for Commands. As I did not find any information in the docs, any ideas how to solve this problem?

mixable
  • 1,068
  • 2
  • 12
  • 42

1 Answers1

1

You can simply instantiate the command and then run it, like this:

try {
    $otherCommand = new \App\Command\OtherCommand();
    $result = $otherCommand->run(['--foo', 'bar'], $io);
} catch (\Cake\Console\Exception\StopException $e) {
    $result = $e->getCode();
}

CakePHP 3.8 will introduce a convenience method that helps with this. Quote from the upcoming docs:

You may need to call other commands from your command. You can use executeCommand to do that::

// You can pass an array of CLI options and arguments.
$this->executeCommand(OtherCommand::class, ['--verbose', 'deploy']);

// Can pass an instance of the command if it has constructor args
$command = new OtherCommand($otherArgs);
$this->executeCommand($command, ['--verbose', 'deploy']);

See also https://github.com/cakephp/cakephp/pull/13163.

ndm
  • 59,784
  • 9
  • 71
  • 110
  • Thank you for this solution. Works perfect! Great to see, that CakePHP 3.8 will provide an additional function for this. – mixable Jun 07 '19 at 18:22