26/07/2015 - SYMFONY
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.
services:
application_backend.command.calculator:
class: Application\BackendBundle\Command\CalculatorCommand
calls:
- [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()
{
$this
->setName('get:total')
->addArgument(
'controller',
InputArgument::REQUIRED,
'What is controller name?'
)
->addArgument(
'primary',
InputArgument::REQUIRED,
'What is primary number?'
)
->addArgument(
'secondary',
InputArgument::OPTIONAL,
'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)
{
$this->logger->info(
sprintf(
'Calling CalculatorCommand from [%s] with [%s] [%s] argument(s) at %s.',
$input->getArgument('controller'),
$input->getArgument('primary'),
$input->getArgument('secondary'),
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. [] []