Symfony - 在服务中注入学说存储库
根据如何将存储库注入到Symfony2 中的服务?就像
acme.custom_repository:
class: DoctrineORMEntityRepository
factory: ['@doctrine.orm.entity_manager', getRepository]
arguments:
- 'AcmeFileBundleModelFile'
但我得到一个例外
无效的服务acme.custom_repository":类"EntityManager5aa02de170f88_546a8d27f194334ee012bfe64f629947b07e4919__CG__DoctrineORMEntityManager"不存在.
Invalid service "acme.custom_repository": class "EntityManager5aa02de170f88_546a8d27f194334ee012bfe64f629947b07e4919__CG__DoctrineORMEntityManager" does not exist.
我怎样才能在 Symfony 3.4 中做到这一点?
How can I do this in Symfony 3.4?
EntityClass 实际上是一个有效的 FQCN 类(当然也使用了 phpstorm 上的复制引用),只是将其重命名,因为其中包含公司名称 :).无论如何更新它.
EntityClass is actually a valid class FQCN (also used copy reference on phpstorm to be sure) , just renamed it because a companies name is in it :). updated it anyway.
BlueM 的解决方案完美运行.如果您不使用自动装配,这里是服务定义:
BlueM's solution works perfectly. In case you are not using autowiring here's the service defintion:
AcmeAcmeBundleRespositoryMyEntityRepository:
arguments:
- '@DoctrineCommonPersistenceManagerRegistry'
- AcmeAcmeBundleModelMyEntity # '%my_entity_class_parameter%'
推荐答案
当您使用 Symfony 3.4 时,您可以使用更简单的方法,使用 ServiceEntityRepository
.只需实现您的存储库,让它extend
class ServiceEntityRepository
,您就可以简单地注入它.(至少在使用自动装配时——我没有在经典 DI 配置中使用它,但我认为它也应该可以工作.)
As you are using Symfony 3.4, you can use a much simpler approach, using ServiceEntityRepository
. Simply implement your repository, let it extend
class ServiceEntityRepository
and you can simply inject it. (At least when using autowiring – I haven’t used this with classic DI configuration, but would assume it should also work.)
换句话说:
namespace AppRepository;
use DoctrineBundleDoctrineBundleRepositoryServiceEntityRepository;
use DoctrineCommonPersistenceManagerRegistry;
class ExampleRepository extends ServiceEntityRepository
{
/**
* @param ManagerRegistry $managerRegistry
*/
public function __construct(ManagerRegistry $managerRegistry)
{
parent::__construct($managerRegistry, YourEntity::class);
}
}
现在,无需任何 DI 配置,您可以在任何地方注入存储库,包括控制器方法.
Now, without any DI configuration, you can inject the repository wherever you want, including controller methods.
一个警告(同样适用于您尝试注入存储库的方式):如果 Doctrine 连接被重置,您将拥有对陈旧存储库的引用.但恕我直言,这是我接受的风险,否则我将无法直接注入存储库..
One caveat (which equally applies to the way you try to inject the repository): if the Doctrine connection is reset, you will have a reference to a stale repository. But IMHO, this is a risk I accept, as otherwise I won’t be able to inject the repository directly..
相关文章