具有唯一实例的Symfony2服务

时间:2014-09-16 11:39:16

标签: symfony service scope singleton

我需要一些帮助:

我有以下服务:

services.yml中的服务配置

服务:

xpad.producto_repository:
     class: Xpad\ProductoBundle\Entity\ProductRepository
     factory_service: doctrine.orm.clientes_entity_manager
     factory_method: getRepository
     arguments:
         - Xpad\ProductoBundle\Entity\Product


backend_cliente.producto_filters:
     class: Xpad\BackendClienteBundle\Filters\ProductFilters
     calls:
         - [setRepository, ["@xpad.producto_repository="]]
     scope: container

和backend_cliente.producto_filters的课程是:

namespace Xpad\BackendClienteBundle\Filters;

use Xpad\ProductoBundle\Entity\ProductRepository;

class ProductFilters
{
    private $_queryBuilder;


    public function getQueryBuilder()
    {
        return $this->_queryBuilder;
    }

    public function setQueryBuilder($queryBuilder)
    {
        $this->_queryBuilder = $queryBuilder;
    }

    public function setRepository(ProductRepository $productRepository = null)
    {
        if($this->_queryBuilder == null)
        {
            $this->_queryBuilder = $productRepository->createQueryBuilder('p');
        }
    }
}

我在我的一个控制器中有以下行动:

class ProductController extends Controller
{ 
 ............
    public function indexAction(Request $request)
    {
      //SOME CODE

       $service_filter = $this->container->get('backend_cliente.producto_filters');
       $queryBuilder = $service_filter->getQueryBuilder();

      //SOME OTHER CODE
    }

我的问题是:indexAction执行的任何时候我得到一个新的backend_cliente.producto_filters服务实例我不知道为什么。我需要并且作为一个单一的独特实例,因为我有一个$ _queryBuilder ATRIBUTTE,我需要获得它的价值,只是在需要的时候修改它的价值;

请帮助我知道我做错了什么。

1 个答案:

答案 0 :(得分:-2)

您是否必须将该课程用作服务?

为什么不使用Singleton而不使用服务?像这样:

namespace Xpad\BackendClienteBundle\Filters;

use Xpad\ProductoBundle\Entity\ProductRepository;

class ProductFilters { 
    private $_queryBuilder;
    private static $reference = null;

    public function getInstance(){
        if (self::$reference === null)
            self::$reference = new ProductFilters();
        return self::$reference;
    }

    private function __construct(){}

    public function getQueryBuilder()
    {
        return $this->_queryBuilder;
    }

    public function setQueryBuilder($queryBuilder)
    {
        $this->_queryBuilder = $queryBuilder;
    }

    public function setRepository(ProductRepository $productRepository = null)
    {
        if($this->_queryBuilder == null)
        {
            $this->_queryBuilder = $productRepository->createQueryBuilder('p');
        }

    }
}

并将其命名为:

...
$filter = ProductFilters::getInstance();
...