Set parameter for Doctrine filter on every request

2019-04-12 23:37发布

问题:

I have a Doctrine filter in Symfony2 project. I am trying to set filter's parameter to some value (taken from session) on every request. The problem is that filter object is created after Symfony's onKernelRequest event, so I can't set it from there. If I try to set it in Doctrine's postConnect event circular dependency is detected:

ServiceCircularReferenceException: Circular reference detected for service "doctrine.orm.private_entity_manager", path: "routing.loader -> assetic.asset_manager -> twig -> translator.default -> doctrine.orm.private_entity_manager -> doctrine.dbal.private_connection -> year_visibility.parameter_setter".

The question is, where (or rather how) should I set filter's parameter?

回答1:

You can try to define filters manually and pass required parameters at the same time.

services:
    app.filter_manager:
        class: App\Bundle\AppBundle\Filter\FilterManager
        arguments: [@doctrine.orm.entity_manager, @session]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

And in the filter manager class:

// ...

public function __construct(EntityManager $em, SessionInterface $session) 
{
    $this->em = $em;
    $this->session = $session;
}

// ...

public function onKernelRequest()
{
    $this->em->getConfiguration()->addFilter('filter_name', 'Filter/Class/Name/With/Ns');

    $filter = $this->em->getFilters()->enable('filter_name');
    $filter->setParameter('param_name', $this->session->get('param_name'));
}  


回答2:

As seen here: https://stackoverflow.com/a/14650403/244058 ,

you can have an instance of your Filter class at kernel boot. So, your instance would be available very early.

<?php

class MyBundle extends Bundle 
{
    public function boot()
    {
        $em = $this->container->get('doctrine.orm.default_entity_manager');
        $conf = $em->getConfiguration();
        $conf->addFilter(
            'filter_name',
            'Doctrine\Filter\TestFilter'
        );

        // either enable it here, or later in the event listener
        $em->getFilters()->enable('filter_name');
    }
}

After that, just add a kernel.event_listener that listens on kernel.request and set a filter parameter (something like this):

<?php

class DoctrineSqlFilterConfigurator
{
    private $em; // inject the entity manager somehow (ctor is a good idea)

    public function onKernelRequest(GetResponseEvent $event)
    {
        $filter = $this->em->getFilters()->enable('filter_name');
        $filter->setParameter('param_name', $event->getRequest()->getSession()->get('param_name'));
    }
}