Symfony2: get Doctrine in a generic PHP class(Symfony2:在通用 PHP 类中获取 Doctrine)
问题描述
在 Symfony2 项目中,当您使用 Controller 时,您可以通过在 this<上调用 getDoctrine() 来访问 Doctrine/code>,即:
In a Symfony2 project, when you use a Controller, you can access Doctrine by calling getDoctrine() on this, i.e.:
$this->getDoctrine();
这样,我就可以访问这样一个Doctrine Entity的仓库了.
In this way, I can access the repository of such a Doctrine Entity.
假设在 Symfony2 项目中有一个通用的 PHP 类.如何检索 Doctrine ?我想应该有这样的服务可以得到它,但我不知道是哪一个.
Suppose to have a generic PHP class in a Symfony2 project. How can I retrieve Doctrine ? I suppose that there is such a service to get it, but I don't know which one.
推荐答案
你可以将这个类注册为一个服务 并向其中注入任何其他服务.假设你有 GenericClass.php 如下:
You can register this class as a service and inject whatever other services into it. Suppose you have GenericClass.php as follows:
class GenericClass
{
public function __construct()
{
// some cool stuff
}
}
您可以将其注册为服务(通常在您的包的 Resources/config/service.yml|xml 中)并将 Doctrine 的实体管理器注入其中:
You can register it as service (in your bundle's Resources/config/service.yml|xml usually) and inject Doctrine's entity manager into it:
services:
my_mailer:
class: Path/To/GenericClass
arguments: [doctrine.orm.entity_manager]
它会尝试将实体管理器注入(默认情况下)GenericClass 的构造函数.所以你只需要为它添加参数:
And it'll try to inject entity manager to (by default) constructor of GenericClass. So you just have to add argument for it:
public function __construct($entityManager)
{
// do something awesome with entity manager
}
如果您不确定应用程序的 DI 容器中有哪些服务可用,您可以使用命令行工具查找:php app/console container:debug,它会列出所有可用的服务以及它们的别名和类.
If you are not sure what services are available in your application's DI container, you can find out by using command line tool: php app/console container:debug and it'll list all available services along with their aliases and classes.
这篇关于Symfony2:在通用 PHP 类中获取 Doctrine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Symfony2:在通用 PHP 类中获取 Doctrine
基础教程推荐
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
