Jea*_*ean 4 php doctrine symfony
在Symfony2中的项目,当你使用一个控制器,可以访问主义致电getDoctrine()上this,即:
$this->getDoctrine();
Run Code Online (Sandbox Code Playgroud)
通过这种方式,我可以访问这样一个Doctrine Entity的存储库.
假设在Symfony2项目中有一个通用的PHP类.我该如何检索Doctrine?我想有这样的服务可以得到它,但我不知道哪一个.
Ond*_*ták 11
您可以将此类注册为服务,并将任何其他服务注入其中.假设您有GenericClass.php,如下所示:
class GenericClass
{
public function __construct()
{
// some cool stuff
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将其注册为服务(Resources/config/service.yml|xml通常在您的包中)并将Doctrine的实体管理器注入其中:
services:
my_mailer:
class: Path/To/GenericClass
arguments: [doctrine.orm.entity_manager]
Run Code Online (Sandbox Code Playgroud)
并且它会尝试将实体管理器注入(默认情况下)构造函数GenericClass.所以你只需要为它添加参数:
public function __construct($entityManager)
{
// do something awesome with entity manager
}
Run Code Online (Sandbox Code Playgroud)
如果您不确定应用程序的DI容器中有哪些服务可用,您可以使用命令行工具找到php app/console container:debug它:它将列出所有可用服务及其别名和类.