Search code examples
phpsymfonysymfony4

Symfony: Calling a custom command from inside a controller


I couldn't find an answer to this.

Not sure if it's relevant to this issue, but my project runs on a Limactl VM in Ubuntu.

I am trying to call a custom command from inside my controller, but I can't make sense of the exception I get as it states that there are no commands defined in the app namespace, yet I can call them from the console just fine.

The command bin/console app:execute {slug} {command} works fine in the terminal, but not when I call it from my controller. Actually, it does the same when I try to run debug:twig.

Could it be that the working directory used is not pointed at the right location? If so, how do I do that and then does that Limactl VM matter in how I tackle this issue?

The method is this:

use Symfony\Bundle\FrameworkBundle\Console\Application;

    protected function executeCommand(String $command,String $slug, KernelInterface $kernel)
    {
      $application = new Application($kernel);
      $application->setAutoExit(false);

      $input = new ArrayInput([
        'command' => "bin/console app:execute",
        'cmd' => $command,
        'slug' => $slug,
      ]);

      $output = new BufferedOutput();
      $application->run($input, $output);

      $content = $output->fetch();

      return $this->render('command_results/index.html.twig', [
        'output' => $content
      ]);
    }

This is the line from my dev.log:

[2023-08-25T15:14:27.095303+00:00] console.CRITICAL: Error thrown while running command "'bin/console app:execute'". Message: "There are no commands defined in the "bin/console app" namespace." {"exception":"[object] (Symfony\\Component\\Console\\Exception\\NamespaceNotFoundException(code: 0): There are no commands defined in the \"bin/console app\" namespace. at /Users/me/dev/runner/runner/vendor/symfony/console/Application.php:622)","command":"'bin/console app:execute'","message":"There are no commands defined in the \"bin/console app\" namespace."} {"uid":"c6e8985","file":"/Users//dev/runner/runner/vendor/symfony/console/EventListener/ErrorListener.php","line":48,"class":"Symfony\\Component\\Console\\EventListener\\ErrorListener","callType":"->","function":"onConsoleError"}

Thanks for any help or advice you can give me! And my apologies if this has actually been asked before and I'm just super blind.


Solution

  • I figured it out: By finding the command to execute using $application->find('command'); and setting that to a variable, I can use that instance to perform $commandInstance->run() and that's it!