如何在 symfony 3 中为存储库类配置依赖注入 [英] How to configure dependency injection for repository class in symfony 3
问题描述
Symfony 生成器生成了以下存储库类:
Symfony generator generated the following class of repository:
namespace AppBundle\Repository;
use AppBundle\Entity\GroupEntity;
/**
* GroupEntityRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class GroupEntityRepository extends \Doctrine\ORM\EntityRepository
{
}
services.yml:
services.yml:
group_entity_repository:
class: AppBundle\Repository\GroupEntityRepository
arguments: ["@doctrine.orm.entity_manager", AppBundle\Entity\GroupEntity]
我错误地配置了 services.yml,但我现在不知道使用什么作为第二个参数.所以我得到了错误:
I configured services.yml wrongly, but I do not now what to use as second argument. So I get the error:
可捕获的致命错误:传递给 Doctrine\ORM\EntityRepository::__construct() 的参数 2 必须是 Doctrine\ORM\Mapping\ClassMetadata 的实例,给出字符串,在 E:\other\dropbox\Dropbox\programavimas\ 中调用kodo pavyzdziai\htdocs\users_admin_demo\var\cache\dev\appDevDebugProjectContainer.php 在线 1626 和定义
Catchable Fatal Error: Argument 2 passed to Doctrine\ORM\EntityRepository::__construct() must be an instance of Doctrine\ORM\Mapping\ClassMetadata, string given, called in E:\other\dropbox\Dropbox\programavimas\kodo pavyzdziai\htdocs\users_admin_demo\var\cache\dev\appDevDebugProjectContainer.php on line 1626 and defined
如何解决?我在文档中看不到,它只显示了生成器和最终生成的类的代码,但没有显示服务配置.
How to fix it? I cannot see in the documentation, it just showed the code for generator and final generated class but no services config.
推荐答案
从 Symfony 3.3 开始推荐:
从 Symfony 3.3 开始,建议使用实际的类名作为服务 id (阅读本 和本).
As of Symfony 3.3 it is recommended to use the actual class name as service id (read this and this).
AppBundle\Repository\GroupEntityRepository:
factory: 'Doctrine\ORM\EntityManagerInterface:getRepository'
arguments:
- AppBundle\Entity\GroupEntity
原答案:
您可以像这样配置您的存储库服务:
You can configure your repository service like this:
group_entity_repository:
class: AppBundle\Repository\GroupEntityRepository
factory: ["@doctrine.orm.entity_manager", getRepository]
arguments:
- AppBundle\Entity\GroupEntity
您可能永远不想自己调用存储库构造函数.因此,这种方法仅使用 entity_manager 来获取存储库.服务容器基本上是使用这个代码来获取仓库的:
You will probably never want to invoke the repository constructor yourself. Therefore this approach just uses the entity_manager to get the repository. The service container bascially uses this code to get the repository:
$container->get('doctrine.orm.entity_manager')->getRepository('AppBundle\Entity\GroupEntity');
这篇关于如何在 symfony 3 中为存储库类配置依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!