在我的项目中,我使用 JMSDIExtraBundle 注释。
我的问题是:我如何告诉我的应用程序存储库应该是服务,这样我就可以使用注释将其注入到另一个服务中。我知道的唯一方法是使用 XML 文件将存储库定义为服务。但这是一个非常缓慢的过程(与简单的 @DI\Service 相比,我更喜欢在 yml 或 xml 文件中定义它)。
我找到了 XML 的替代解决方案,但我认为这是个坏主意:
####CustomService.php####
/**
* @param EntityManager $em
*
* @DI\InjectParams({
* "em" = @DI\Inject("doctrine.orm.entity_manager")
* })
*/
public function __construct(EntityManager $em) {
$this->em = $em;
}
以及服务中的某个地方:
$entityRepository = $this->em->getRepository(AcmeBundle:Entity);
当我需要使用存储库时,有什么想法可以加快编码过程吗?
您可以将实体存储库定义为服务并将其注入到服务中。
作为示例,您可以将存储库配置为服务,如下所示:
在标准的 Symfony 服务定义方式中:
####service.xml####
<service id="acme.user.repository"
class="Doctrine\ORM\EntityRepository"
factory-service="doctrine.orm.entity_manager"
factory-method="getRepository">
<argument>AcmeDemoBundle:User</argument>
</service>
或者使用factory to Service annotation
在 JMSDiExtraBundle 中定义(参见this https://github.com/schmittjoh/JMSDiExtraBundle/pull/115):
/**
* @Service("acme.user.repository", factoryService = "doctrine", factoryMethod="getRepository", factoryMethodArguments={
* "persistentObjectName" = "Acme\DemoBundle\Entity\User"
* } )
*/
并注入并将其用作:
####CustomService.php####
/**
* @param Doctrine\ORM\EntityRepository $repo
*
* @DI\InjectParams({
* "repo" = @DI\Inject("acme.user.repository")
* })
*/
public function __construct(EntityRepository $repo) {
$this->repo = $repo;
}
加速不是很大,但只允许注入您需要的内容
希望这有帮助
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)