【问题标题】:Symfony2: Using a repository in a commandSymfony2:在命令中使用存储库
【发布时间】:2015-11-03 23:37:11
【问题描述】:

我正在使用 Symfony2 (2.6),我想在名为 CRM:fetchEmails 的命令中使用联系人实体的自定义存储库。

我尝试了两种不同的方法来获取存储库:

第一种方法:

在我的命令文件的执行函数中

$repository = $this->getContainer()->get('doctrine')->getEntityManager()->getRepository('CRMBundle:Contact');

第二种方法:

在我的命令文件的执行函数中

$repository = $this->getContainer()->get('myrepository');

在 config.yml 中

myrepository:
    class: Doctrine\ORM\EntityRepository
    factory: [@doctrine.orm.entity_manager, getRepository]
    arguments:
        - CRMBundle\Entity\Contact

第一种或第二种方法在执行命令时出现此错误:

 [Symfony\Component\Debug\Exception\ContextErrorException] Notice: Undefined property: Doctrine\ORM\Configuration::$getRepository CRM:fetchEmails [name] 

有人知道如何解决我的问题吗?

【问题讨论】:

  • 显示您使用 fetchEmails 的部分。听起来你忘记了一些括号

标签: php symfony doctrine-orm


【解决方案1】:

我会继承ContainerAwareCommand来解决这个问题:

public class MyCommand extends ContainerAwareCommand
{ ... }

ContainerAwareCommand 是 Command 的基类,但可以访问容器(就像您在基于 Controller 的类中所做的那样,因此您可以通过 $this->getContainer()->getDoctrine()->getRepository("BundleName:MyRepo") 访问您的存储库。

如果有帮助请告诉我!

【讨论】:

  • 错误信息暗示容器已经可用。
【解决方案2】:

从 Symfony2.8 你可以这样做:

             $doctrine = $this->getContainer()->get('doctrine');
             $em = $doctrine->getEntityManager();
             $usersRepo= $doctrine->getRepository('ApplicationSonataUserBundle:User');
             $user= $usersRepo->find(1);
             $em->persist($$user);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多