Symfony 如何在不传递参数的情况下获取repository类中的容器对象?

Symfony 如何在不传递参数的情况下获取repository类中的容器对象?,symfony,Symfony,我如何在不传递消息的情况下获取repository类中的容器对象 参数 您将获得容器对象,如下所示: // include files to get container use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerAwareInterface; class ClassNameRepository extends E

我如何在不传递消息的情况下获取repository类中的容器对象 参数


您将获得容器对象,如下所示:

// include files to get container
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;

class ClassNameRepository extends EntityRepository implements ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     *
     * @author Ashok Chitroda <ashok.chitroda@gmail.com>
     */
    private $container;

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


Ashok Chitroda

您将获得如下容器对象:

// include files to get container
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;

class ClassNameRepository extends EntityRepository implements ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     *
     * @author Ashok Chitroda <ashok.chitroda@gmail.com>
     */
    private $container;

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


Ashok Chitroda

它可以工作,但不要这样做。一般来说,这是一种不好的做法。通过注入一个容器,你注入了整个世界的服务,这基本上使你的存储库依赖于任何东西。@Jakub Zalas,还有其他方法吗?@ChintanMirani是的。正确设计,不要赋予实体不属于它们的责任。如果确实需要将服务传递给实体,请显式传递,并在需要该服务的方法调用中传递该服务。不理想,但至少您的实体依赖项是可见的。它可以工作,但不要这样做。一般来说,这是一种不好的做法。通过注入一个容器,你注入了整个世界的服务,这基本上使你的存储库依赖于任何东西。@Jakub Zalas,还有其他方法吗?@ChintanMirani是的。正确设计,不要赋予实体不属于它们的责任。如果确实需要将服务传递给实体,请显式传递,并在需要该服务的方法调用中传递该服务。不理想,但至少您的实体依赖关系是可见的。