CakePHP: Execute Shell Command from Controller

CakePHP provides a full featured console tools to execute tasks such as cron job, sending weekly emails or any background process which does not require http request handling. It provides several basic core Shells like Bake, Migrations etc.

You can execute these shell commands from command prompt. See here for details.

Now the question is: How to execute shell command from the controller? For example, there is a shell created to do some common tasks and you need to execute it from your controller’s action.

To do so, we can use ShellDispatcher. Consider the following Shell,

You can execute the above shell command from command prompt using following command,

Execute shell from controller

Now, to execute this Foo shell from our controller, use the ShellDispatcher from your Controller’s action like,

Here, pass the arguments in array format. First element should be the cake shell and others will be arguments. In above example, it will consider cake as command and foo as it’s argument (or sub-command).

Pass arguments

You can pass the arguments of your shell command as described above. Let’s modify our FooShell like,

By running following command in prompt will show the name passed as an argument.

Now, in our controller’s action, pass the argument as an element of array like,

You can pass sub-command as an argument as well. For example, there is a Bar task in Foo shell, and one argument in Bar’s main() function, you can use following,

Execute shell from plugin

Iif you want to execute Foo shell from Bar plugin, simply pass the plugin name as extra parameter like,

That is it!

You may also like...