如何在Symfony中的Console命令中使用实体

时间:2016-02-18 12:34:38

标签: php symfony

如何在控制台命令中使用doctrine和entity?在控制器中,我只需执行$ this-> getDoctrine ...,但在Command中我发现我必须使用容器,$ this-> getContainer() - > getDoctrine()但这会生成控制台错误:

  

由于尚未设置应用程序实例,因此无法检索容器。

     谷歌没有帮助我......

1 个答案:

答案 0 :(得分:0)

我在使用Symfony 3的命令中找到了一篇很好的文章

// myapplication/src/sandboxBundle/Command/TestCommand.php
// Change the namespace according to your bundle
namespace sandboxBundle\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
// Add the Container
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

//Extend ContainerAwareCommand instead of Command
class TestCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            // the name of the command (the part after "bin/console")
            ->setName('app:verify-doctrine')
            // the short description shown while running "php bin/console list"
            ->setHelp("This command allows you to print some text in the console")
            // the full command description shown when running the command with
            ->setDescription('Prints some text into the console with given parameters.')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln([
            'My Final Symfony command',// A line
            '============',// Another line
            '',// Empty line
        ]);

        $doctrine = $this->getContainer()->get('doctrine');
        $em = $doctrine->getEntityManager();

        // Now you can get repositories
        // $usersRepo = $em->getRepository("myBundle:Users");
        // $user = $usersRepo->find(1);

        // outputs multiple lines to the console (adding "\n" at the end of each line)

        $output->writeln("Doctrine worked, it didn't crashed :) ");

        // Instead of retrieve line per line every option, you can get an array of all the providen options :
        //$output->writeln(json_encode($input->getOptions()));
    }
}

如果您需要更多信息http://ourcodeworld.com/articles/read/239/how-to-create-and-execute-a-custom-console-command-in-symfony-3

,以下是该网站的链接