我试图创建一个Symfony2的服务,以自动传递到Doctrine\ORM\EntityManager
到__construct
避免到每个I类实例化时通过它,即@ doctrine.orm.entity_manager不给予注册为服务类
// use this
$TestClass= new TestClass;
// instead of this
$entityManager = $this->getDoctrine()->getEntityManager();
$TestClass= new TestClass($entityManager);
我创建了一个EntityManagerUser类,试图将它注册为一个服务,TestClass扩展了它。 包含services.yml,因为另一个服务可以工作,并且我通过添加(然后删除)语法错误来进行双重检查。
我阅读文档,this,this和this和我已经结束了与下面的代码,其不通过@doctrine.orm.entity_manager
。但是,controller_listener服务确实收到@templating
。
我已经通过控制台清除缓存和手动删除应用程序/缓存,但我还是看到此错误:
ContextErrorException: Catchable Fatal Error: Argument 1 passed to Test\TestBundle\ServiceUser\EntityManagerUser::__construct() must be an instance of Test\TestBundle\ServiceUser\Doctrine\ORM\EntityManager, none given, called in D:\Documents\www\Test\live\src\Test\TestBundle\Controller\MyController.php on line 84 and defined in D:\Documents\www\Test\live\src\Test\TestBundle\ServiceUser\EntityManagerUser.php line 14
services.yml
services:
# this one doesn't throw an error and passes @templating to __construct
test.eventlistener.before_controller_listener:
class: Test\TestBundle\Eventlistener\BeforeControllerListener
arguments: [ @templating ]
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
# the following one doesn't pass @doctrine.orm.entity_manager
test.service_user.entity_manager_user:
class: Test\TestBundle\ServiceUser\EntityManagerUser
arguments: [ @doctrine.orm.entity_manager ]
的src /测试/TestBundle/ServiceUser/EntityManagerUser.php
namespace Test\TestBundle\ServiceUser;
use Doctrine\ORM\EntityManager;
class EntityManagerUser{
protected $entityManager;
public function __construct(EntityManager $entityManager){
$this->entityManager = $entityManager;
// N.B. it's not possible to do it this way:
// $this->entityManager = new EntityManager;
}
// also tried public function __construct($entityManager){
// and public function __construct(Doctrine\ORM\EntityManager $entityManager){
}
的src /测试/ TestBundle /班/ TestClass.php
namespace Test\TestBundle\Classes\TestClass;
use Test\TestBundle\ServiceUser\EntityManagerUser;
class TestClass extends EntityManagerUser{
/* currently no functions */
}
在我的控制器,线路84
$test= new TestClass;
// I tested that this throws the same error, it does // $test= new EntityManagerUser;
有什么我错过了?
感谢。所以我不能为EntityManagerUser定义一个服务,然后扩展这个类,我必须将每个类定义为一个服务,我想将entity_manager注入到该服务中? – Popnoodles
我很遗憾地说,但是,只是扩展宣布为服务的类是不够的。 – Chausser
好吧,那就是我想要避免的行数越少越好。只是宣布它是全球性的,这很诱人。 – Popnoodles