Symfony2 - 存储库中的getParameter

Hel*_*ert 2 parameters entity repository symfony

如何从实体存储库访问我的parameters.yml文件中的参数?

我可以从控制器访问它:

$this->container->getParameter('deadline_for_privileged');
Run Code Online (Sandbox Code Playgroud)

但我似乎无法在我的存储库中获取容器......它是一个标准的实体存储库,由doctrine生成.

Spotrepository

<?php

namespace Prophets\ParkingBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * SpotRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class SpotRepository extends EntityRepository
{

    protected function setSpotStatus($spot){
        //method that compares database values with a fixed deadline - the parameter. 
        //It returns if it's earlier/later than the deadline


        $deadline = $this->container->getParameter("deadline_for_privileged");
    }
}
Run Code Online (Sandbox Code Playgroud)

任何人?

Mar*_*nte 6

最简单的方法是使用jms/di-extra-bundle注释仅使用如下方法注入参数:

use JMS\DiExtraBundle\Annotation as DI;
use Doctrine\ORM\EntityRepository;

class SpotRepository extends EntityRepository
{

/**
 * @DI\InjectParams({
 *     "param" = @DI\Inject("%app.param%")
 * })
 */
public function setParam($param)
{
    $this->param = $param;
}
Run Code Online (Sandbox Code Playgroud)

这样你就会尊重SRP和demeter定律.

另一种方式(没有外部捆绑但缺乏依赖注入的方面)是使用containeraware接口注入容器

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;

use Doctrine\ORM\EntityRepository;

class SpotRepository extends EntityRepository implements ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }
    ...
Run Code Online (Sandbox Code Playgroud)

最后一种方式(但"最正确的方式")是创建一个专用服务(SpotManager),它与构造函数中的存储库和参数一起使用(使用依赖注入).这使您可以轻松维护存储库并提供服务,而服务又可以保持轻量级.