6

I have found a lot of documentation on how to run Drush commands from code, but I'm specifically looking on how to run a Drupal Console command from code.

I have some experience in Symfony and I know how to run a Symfony command from code. Since a Drupal console command extends on Symfony command, I thought this should be rather easy. Simply following this tutorial doesn't amount to anything though.

I am trying to run a command in a hook_cron() implementation in a custom module.

4
  • 1
    Please elaborate why you would downvote my question. I've spend close to an hour in the code and over an hour on the internet for a solution, but I just can't get there.
    – Loek
    Jun 28, 2017 at 13:35
  • What if you use the php functions exec() or shell_exec() ? I haven't done it before but it's the first thing I would try. Jun 28, 2017 at 15:55
  • It's weird how you can become so fixated on doing it 1 way that forget about the other, way easier ways.. Will accept as answer if you add it ;)
    – Loek
    Jun 28, 2017 at 16:11
  • 1
    Thanks. I've added the answer with refernces to the php docs to help others as well Jun 28, 2017 at 16:24

2 Answers 2

3

Try using the PHP functions exec() or shell_exec().

1
  • 1
    But do so carefully and responsibly.
    – Kevin
    Jun 28, 2017 at 17:01
8

Run shell commands via the Process class available in the Symfony framework.

From the Symfony docs:

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

$process = new Process('ls -lsa');
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();

The component takes care of the subtle differences between the different platforms when executing the command.

Replace the ls -lsa command in the Process() constructor with your Drupal console command.

2
  • This is more in the way I was looking for indeed. Sticking with exec for now since there aren't any parameters and the command is fixed, but this is nice for better handling of your commands.
    – Loek
    Jun 28, 2017 at 17:30
  • Thank you, this approach looks good. There is a function drush_shell_exec_interactive which shows more imformation for interactive commands, like drush cim -y. But it is deprecated. I am still looking for a replacement for this function.
    – milkovsky
    Sep 30, 2020 at 11:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.