Dependency injection Symfony2中的依赖项注入到底做什么?
我注册了services.yml文件,如下所示:Dependency injection Symfony2中的依赖项注入到底做什么?,dependency-injection,symfony,Dependency Injection,Symfony,我注册了services.yml文件,如下所示: services: PMI.form.users_tasks: class: PMI\UserBundle\Form\UsersTasksType arguments: EntityManager: "@doctrine.orm.default_entity_manager" class UsersTasksType extends AbstractType { prot
services:
PMI.form.users_tasks:
class: PMI\UserBundle\Form\UsersTasksType
arguments:
EntityManager: "@doctrine.orm.default_entity_manager"
class UsersTasksType extends AbstractType
{
protected $ur;
public function __construct(EntityManager $ur )
{
$this->setUr($ur);
}
// Get and setters
}
我可以通过php应用程序/控制台容器:debug
列出它,这意味着我的服务注册正确
在我的UsersTasksType类中,我有如下内容:
services:
PMI.form.users_tasks:
class: PMI\UserBundle\Form\UsersTasksType
arguments:
EntityManager: "@doctrine.orm.default_entity_manager"
class UsersTasksType extends AbstractType
{
protected $ur;
public function __construct(EntityManager $ur )
{
$this->setUr($ur);
}
// Get and setters
}
依赖注入是否意味着我不再需要将EntityManager
传递给类构造函数?还是什么
因为当我必须运行下面的代码时:
$form = $this->createForm(new UsersTasksType(), $entity);
我得到这个错误:
Catchable Fatal Error: Argument 1 passed to PMI\UserBundle\Form\UsersTasksType::__construct() must be an instance of Doctrine\ORM\EntityManager, none given, called in C:\wamp\www\PMI_sf2\src\PMI\UserBundle\Controller\UsersTasksController.php on line 74 and defined in C:\wamp\www\PMI_sf2\src\PMI\UserBundle\Form\UsersTasksType.php line 19
我必须做以下几件事:
$em = $this->container->get('doctrine.orm.entity_manager');
$form = $this->createForm(new UsersTasksType($em), $entity);
那么依赖注入的全部目的是什么呢 依赖项注入基本上是让一个服务(在本例中是您的UserTasksType)访问另一个服务(在本例中是您的实体管理器) 这两行告诉Symfony,当您实例化新的UserTasksType对象时,实体管理器服务将被传递到构造函数中,这将有效地为您的UserTasksType提供访问实体管理器的权限
arguments:
EntityManager: "@doctrine.orm.default_entity_manager"
如果您没有在UserTasksType中使用实体管理器,则无需将其注入构造函数,您可以在UserTasksType中去掉上面的两行和\uu construct()
/setUr()
方法
帮助您理解DIC的一个更好的例子可能是,您有一个专门为发送电子邮件而编写的服务(例如,Swiftmail),您需要将其注入另一个服务中,以便该服务可以发送电子邮件
加入
arguments: [ @mailer ]
根据您的服务定义,您的服务构造函数将期望您的邮件服务
__construct ($mailer)
{
$this->mailer = $mailer;
}
这将使它能够发送电子邮件
someFunction()
{
//do something useful, then send an email using the swift mailer service
$this->mailer->sendEmail();
}
查看最新的Symfony文档,了解更多解释
谢谢你的解释,但是为什么我会得到这个可捕获的致命错误?因为在你的UsersTasksType类的构造函数中,你告诉它需要一个实体管理器:public function\uu构造(EntityManager$ur),你用新的UsersTasksType()实例化它——也就是说,你没有给它一个实体管理器。好的,因此,当我使用
NEW
实例化时,我必须将EntityManager
传递给我的类,但是当使用$this->container->get('the_service')代码>它将被自动注入。对吗?不,当你实例化一个类的新实例时,你总是必须使用new。区别在于您是否在正在实例化的类的构造函数中定义了实体管理器(或任何其他服务)。