【问题标题】:Symfony2, use getDoctrine and em in classSymfony2,在课堂上使用 getDoctrine 和 em
【发布时间】:2014-09-17 13:54:12
【问题描述】:

我在 Symfony2 中有一个 Timesheet.php 类,我需要在这个类中使用例如:

$this->getDoctrine()->getRepository()->find();
$this->getDoctrine()->getManager()->remove();

我该怎么做?我尝试将类调用为服务,在构造函数中手动添加变量等但没有效果...

你有好的解决方案吗?

【问题讨论】:

    标签: symfony doctrine


    【解决方案1】:

    这是因为$this->getDoctrine()Symfony\Bundle\FrameworkBundle\Controller 类的方法。当您检查此方法时,有$this->container->get('doctrine') 所以您需要在您的Timesheet 类中提供doctrine。为此,请将您的 Timesheet 类定义为服务:

    your.service_id:
        class: Acme\DemoBundle\Timesheet
        arguments: [@doctrine]
    

    然后你的Timesheet 班级:

    use Doctrine\Bundle\DoctrineBundle\Registry;
    
    class Timesheet
    {
        /**
         * @var Registry
         */
        private $doctrine;
    
        /**
         * @param Registry $doctrine Doctrine
         */
        public function __construct(Registry $doctrine)
        {
            $this->doctrine = $doctrine;
        }
    
        public function yourMethod()
        {
            //this is what you want to achieve, right?
            $this->doctrine->getManager()->remove();
            $this->doctrine->getRepository()->find();
        }
    }
    

    【讨论】:

    • 当然,除非 TimeSheet 是从数据库中加载的。这种事情应该避免,但你可以这样做:stackoverflow.com/questions/25795417/…
    • @Cerad 为什么要避免这件事?我很好奇,因为我也使用过这种方法。
    • 基本思想是 Doctrine 2 实体真的不需要知道数据库的细节。对象关系管理器(ORM)应该关注对象而不是数据库表。这绝对是一种设计应用程序的不同方式。另外,当然,使用全局变量通常是不受欢迎的。在这种特殊情况下,当加载时间表对象时,它应该已经与它需要知道的任何对象有所有关系。因此应该不需要访问存储库。
    猜你喜欢
    • 2012-07-18
    • 2019-05-13
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多