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.

  • 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 '17 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. – Rick Bergmann Jun 28 '17 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 '17 at 16:11
  • 1
    Thanks. I've added the answer with refernces to the php docs to help others as well – Rick Bergmann Jun 28 '17 at 16:24

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

| improve this answer | |
  • 1
    But do so carefully and responsibly. – Kevin Jun 28 '17 at 17:01

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');

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

| improve this answer | |
  • 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 '17 at 17:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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