我在Symfony2的项目学说过滤器。 我试图过滤器的参数设置为每个请求一些值(从会议上作出)。 问题是,过滤对象的Symfony的onKernelRequest事件之后创建的,所以我不能在那里设置。 如果我尝试将其设置成学说的postConnect事件循环依赖检测:
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".
现在的问题是,在(或者说如何)我应该设置过滤器的参数?
您可以尝试手动定义过滤器和在同一时间传递所需的参数。
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 }
而在过滤器管理器类:
// ...
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'));
}
正如在这里看到: https://stackoverflow.com/a/14650403/244058 ,
你可以在内核引导有你的过滤器类的一个实例。 所以,你的情况是可以非常早。
<?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');
}
}
之后,只需添加上侦听kernel.event_listener kernel.request
并设置过滤器参数(像这样):
<?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'));
}
}