Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

We can create a console command to do some work for us and return a result after calling it from a controller. Example below multiplies given numbers, returns the result and takes a log.


class: Application\BackendBundle\Command\CalculatorCommand
- [setContainer, [@service_container]]


namespace Application\BackendBundle\Command;

use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class CalculatorCommand extends ContainerAwareCommand
* @var $logger LoggerInterface
private $logger;

protected function configure()
'What is controller name?'
'What is primary number?'
'What is secondary number?'
->setDescription('This multiplies given numbers.');

protected function initialize(InputInterface $input, OutputInterface $output)
$this->logger = $this->getContainer()->get('logger');

protected function execute(InputInterface $input, OutputInterface $output)
'Calling CalculatorCommand from [%s] with [%s] [%s] argument(s) at %s.',
date('Y-m-d H:i:s')

return $input->getArgument('primary') * $input->getArgument('secondary');


Assuming that you've injected @application_backend.command.calculator into controller via controllers.yml file.

namespace Application\BackendBundle\Controller;

use Application\BackendBundle\Command\CalculatorCommand;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\HttpFoundation\Response;

class ApiController extends AbstractController

public function indexAction()
$input = new ArrayInput(['controller'=> 'ApiController', 'primary'=> 5, 'secondary'=> 3]);
$output = new NullOutput();
$result = $this->calculatorCommand->run($input, $output);

return new Response($result);


If you call controller above, the response will be 15 and the log record in dev.log file will contain line below.

[2015-07-26 17:02:35] app.INFO: Calling CalculatorCommand from [ApiController] with [5] [3] argument(s) at 2015-07-26 17:02:35. [] []