RenderView in Symfony Command usage

后端 未结 3 2191
迷失自我
迷失自我 2021-02-20 08:52

How can I use $this->renderView inside a symfony Command (not inside a controller)? I new about the function \"renderView\" but what do I have to setup to use it wihtin a comman

3条回答
  •  臣服心动
    2021-02-20 09:29

    Yet another one: rely on dependency injection, i.e. inject ContainerInterface

    namespace AppBundle\Command;
    
    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    use Psr\Container\ContainerInterface;
    
    class SampleCommand extends Command
    {
        public function __construct(ContainerInterface $container)
        {
            $this->templating = $container->get('templating');
            parent::__construct();
        }
    
        protected function configure()
        {
            $this->setName('app:my-command')
                 ->setDescription('Do my command using render');
        }
    
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $data = retrieveSomeData();
            $csv = $this->templating->render('path/to/sample.csv.twig',
                                             array('data' => $data));
            $output->write($csv);
        }
    
        private $templating;
    }
    

    This relies on Symfony to inject the container, which in turn is used to retrieve either templating or twig or whatever you need for your custom command.

提交回复
热议问题