Skip to content

Instantly share code, notes, and snippets.

@devdrops
Created September 18, 2015 20:50
Show Gist options
  • Save devdrops/a89c00cffc7617b2078e to your computer and use it in GitHub Desktop.
Save devdrops/a89c00cffc7617b2078e to your computer and use it in GitHub Desktop.
Calling a command from a controller, and get it's output.

As described in https://gist.github.com/cordoval/3487715 (thanks for https://twitter.com/cordoval)

<?php

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;

/**
 * @Route("/test")
 */
class SomeController extends Controller
{
    /**
     * @Route("/command")
     */
    public function someAction()
    {
        // Create the application, so that it can collect all the commands
        $application = new Application($this->getContainer()->get('kernel'));
        $application->setAutoExit(false);
        
        // The input interface should contain the command name, and whatever arguments the command needs to run
        $input = new ArrayInput(array("doctrine:schema:update"));
        $output = new MemoryWriter();
        
        // Run the command
        $retval = $application->run($input, $output);

        if(!$retval)
        {
            echo "Command executed successfully!\n";
        }
        else
        {
            echo "Command was not successful.\n";
        }
        var_dump($output->getOutput());
    }
}

And the MemoryWriter class (from https://github.com/predakanga/CronBundle/blob/master/Command/MemoryWriter.php, described at http://stackoverflow.com/questions/17143476/call-console-command-from-controller-and-read-the-output-in-symfony-2-2):

<?php
namespace ColourStream\Bundle\CronBundle\Command;

use Symfony\Component\Console\Output\Output;

/**
 * MemoryWriter implements OutputInterface, writing to an internal buffer
 */
class MemoryWriter extends Output {
    protected $backingStore = "";
    
    public function __construct($verbosity = self::VERBOSITY_NORMAL) {
        parent::__construct($verbosity);
    }

    public function doWrite($message, $newline) {
        $this->backingStore .= $message;
        if($newline) {
            $this->backingStore .= "\n";
        }
    }
    
    public function getOutput() {
        return $this->backingStore;
    }
    
    public function clear() {
        $this->backingStore = "";
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment