恕我直言,这不需要,因为你可能很容易违反类似的规则SRP and 得墨忒耳定律
但如果您确实需要它,可以使用以下方法:
首先,我们定义一个基类“ContainerAwareRepository”,它有一个调用“setContainer”
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;
}
}
然后,我们可以定义我们的模型存储库。
我们在这里使用的学说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