gpt4 book ai didi

php - Symfony2 : How to access to service from repository

转载 作者:可可西里 更新时间:2023-10-31 22:17:50 25 4
gpt4 key购买 nike

我有 ModelsRepository 类:

class ModelsRepository extends EntityRepository
{}

和服务

container_data:
class: ProjectName\MyBundle\Common\Container
arguments: [@service_container]

我想从 ModelsRepository 获得对服务 container_data 的访问权限。我无法从 Controller 使用的构造函数传输服务。

你知道怎么做吗?

最佳答案

恕我直言,这不是必需的,因为您可能很容易违反 SRP 等规则和 Law of Demeter

但是如果你真的需要它,这里有一个方法可以做到这一点:

首先,我们定义了一个名为“setContainer”的“ContainerAwareRepository”基类

services.yml

services:
# This is the base class for any repository which need to access container
acme_bundle.repository.container_aware:
class: AcmeBundle\Repository\ContainerAwareRepository
abstract: true
calls:
- [ setContainer, [ @service_container ] ]

ContainerAwareRepository 可能看起来像这样

AcmeBundle\Repository\ContainerAwareRepository.php

abstract class ContainerAwareRepository extends EntityRepository
{
protected $container;

public function setContainer(ContainerInterface $container)
{
$this->container = $container;
}
}

然后,我们可以定义我们的模型库。
我们在这里使用 doctrine 的 getRepository 方法来构建我们的存储库

services.yml

services:
acme_bundle.models.repository:
class: AcmeBundle\Repository\ModelsRepository
factory_service: doctrine.orm.entity_manager
factory_method: getRepository
arguments:
- "AcmeBundle:Models"
parent:
acme_bundle.repository.container_aware

然后,只需定义类

AcmeBundle\Repository\ModelsRepository.php

class ModelsRepository extends ContainerAwareRepository
{
public function findFoo()
{
$this->container->get('fooservice');
}
}

为了使用存储库,您绝对需要先从服务中调用它。

$container->get('acme_bundle.models.repository')->findFoo(); // No errors
$em->getRepository('AcmeBundle:Models')->findFoo(); // No errors

但如果你直接这样做

$em->getRepository('AcmeBundle:Models')->findFoo(); // Fatal error, container is undefined

关于php - Symfony2 : How to access to service from repository,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12971552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com