Command execution from Controller

Created custom commands to import the data(Not a shell comand), I want to execute the command from the controller, Let me know how can I execute the command in cakephp4 controller.

I tried to use
use Cake\Console\CommandRunner;

$command = new CommandRunner();

But I am getting below error while creating object**($command = new CommandRunner();)**
“Too few arguments to function Cake\Console\CommandRunner::__construct()”

Seems pretty straight-forward. The constructor for that class needs parameters; it needs at least a ConsoleApplicationInterface object.

If the comand spends more time than the maximum request time (usually 30-40 seconds), the executing commands is killed when reaches that limit.

I suggest creating a process with that command, so that the request finishes quickly. The command should be responsible to update process progress somewhere (like having a tasks model and update percent there)

Create a new process like this: (launch ExampleCommand)

    'sh -c "php -d memory_limit=512M ' . ROOT .
    '/bin/cake.php Example ' . $params .
    ' > /dev/null 2>&1 &"'

For more advanced queue plugins you can use:

1 Like

Did anyone solved this? Got the same issue and the reply from Zuluru is not realy helpfull ^^

If you’re getting the exact same error as the OP was, then my reply should be helpful. If you’re getting some other issue, then of course it would not be.

The initial question was: How can I execute a command inside a controller?

The answer to this is: DONT

You should instead refactor your logic into a generic utility/service class which you then call in your command as well as in your controller.

See my CakeFest talk explaining exactly this issue: CakeFest Virtual 2021 Day 2 - How to re use code: Utility Classes and PHP Namespaces - Kevin Pfeifer - YouTube


Thankyou I was just about to make a mess of trying to shoe horn CommandRunner into a controller. I greatly appreciate your contributions of knowledge Kevin.