【问题标题】:Symfony2 - How to access the service in a custom console command?Symfony2 - 如何在自定义控制台命令中访问服务?
【发布时间】:2013-10-19 17:56:24
【问题描述】:

我是 Symfony 的新手。我创建了一个自定义命令,其唯一目的是从系统中擦除演示数据,但我不知道如何执行此操作。

在控制器中我会这样做:

$nodes = $this->getDoctrine()
    ->getRepository('MyFreelancerPortfolioBundle:TreeNode')
    ->findAll();

$em = $this->getDoctrine()->getManager();
foreach($nodes as $node)
{
    $em->remove($node);
}
$em->flush();

从我得到的命令中的 execute() 函数执行此操作:

Call to undefined method ..... ::getDoctrine();

如何通过 execute() 函数执行此操作?此外,如果有更简单的方法来擦除数据而不是循环遍历它们并删除它们,请随时提及。

【问题讨论】:

标签: php symfony console command


【解决方案1】:

Symfony 3.3(2017 年 5 月)开始,您可以轻松地在命令中使用依赖注入。

只需在您的services.yml 中使用PSR-4 services autodiscovery

services:
    _defaults:
        autowire: true

    App\Command\:
        resource: ../Command

然后使用常见的构造函数注入,最后即使Commands 也会有干净的架构:

final class MyCommand extends Command
{
    /**
     * @var SomeDependency
     */
    private $someDependency;

    public function __construct(SomeDependency $someDependency)
    {
        $this->someDependency = $someDependency;

        // this is required due to parent constructor, which sets up name 
        parent::__construct(); 
    }
}

Symfony 3.4(2017 年 11 月)以来,这将(或已经这样做,取决于阅读时间)成为标准,当时commands will be lazy loaded

【讨论】:

  • 如何在 Symfony\Bundle\FrameworkBundle\Console\Application() 中注册这些命令?
【解决方案2】:

为了能够访问服务容器,您的命令需要扩展 Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand

请参阅命令文档章节 - Getting Services from the Container

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
// ... other use statements

class MyCommand extends ContainerAwareCommand
{
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get('doctrine')->getEntityManager();
        // ...

【讨论】:

    猜你喜欢
    • 2013-10-19
    • 2014-02-23
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    相关资源
    最近更新 更多