获取教义或传递服务而不使用__construct - Symfony2 [英] Get Doctrine or pass in service without using __construct - Symfony2

查看:96
本文介绍了获取教义或传递服务而不使用__construct - Symfony2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试扩展一个类,但是我有这个问题:

I'm trying to extend a class, but I have this problem:

(1)我需要进行一个简单的数据库查询,但是如果我传入@ doctrine.orm.entity_manager在services.yml然后我需要传递一个其他的值,并调用parent :: __构造(对于父类),我只是不能让它工作(另一个问题存在,但没有运气)

(1) I need to conduct a simple database query, but if I pass in @doctrine.orm.entity_manager in services.yml I then need to pass a load of other values in and call parent::__construct (for the parent class) and I just can't get it working (another question exists for that but no luck).

(2)如果我不在我的新扩展类中创建一个__construct,那么它可以工作,但是我无法访问进行数据库查询。

(2) If I don't create a __construct in my new extended class then it works but I can't get access to conduct the DB query.

有没有办法访问Doctrine,进行查询,传递@ doctrine.orm.entity_manager或任何内容,以便我可以执行此查询,而无需调用_ 构造我的新的扩展类(并避免必须传递所有这些变量,然后调用这个引起这种问题的父:: _construct)。

Is there a way of getting access to Doctrine, conducting a query, passing in @doctrine.orm.entity_manager or anything so I can conduct this query without having to call a _construct on my new, extended class (and avoid having to pass in all those variables to then call the parent::_construct which is causing such a problem).

正如我一直试图这样做2天,我会采取任何黑客,如果我必须(最好不要太多的hac k,但如果我不能这样做,我可能需要)。到目前为止,我从来没有和Symfony2进行过黑客攻击,所以对我来说这是不常见的。谢谢。

As I have been trying to do this for 2 days then I will take any hack if I have to (preferably not too much of a hack, but I may need to if I can't do this soon). To date I have never resorted to a hack with Symfony2, so this isn't usual for me. Thanks.

推荐答案

您可以使用 setter注入,如果您不想将参数注入到构造函数中。

You can use setter injection if you don't want to inject the arguments into the constructor.

服务配置

 my_service:
     class: YourClass
     calls:
         - [setEntityManager, ["@doctrine.orm.entity_manager"]]

YourClass

use Doctrine\Common\Persistence\ObjectManager;

// ...

protected $em;

public function setEntityManager(ObjectManager $em)
{
   $this->em = $em;
}

public function someOtherFunction()
{
    $this->em->getRepository('...')
}

这篇关于获取教义或传递服务而不使用__construct - Symfony2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆