【问题标题】:Symfony 5 + Doctrine - 根据当前用户为每个请求添加一个过滤器
【发布时间】:2022-01-23 14:12:07
【问题描述】:

我正在尝试对我的控制器的某些操作动态设置“tenant_id”过滤器。

我构建了一个扩展 SQLFilter 的类,并在 addFilterConstraint 中放入了执行此操作的逻辑。

问题在于动态“租户”参数:

如果我将这段代码放在我的每个控制器操作中,它就会起作用:

$em->getFilters()->getFilter('tenant')->setParameter('tenant_id', $security->getUser()->getTenant()->getId());

当然,这是不可维护的,所以我试图将这个逻辑移到其他地方,以使其更清晰,更易于维护。

我正在考虑类似事件,但是当Security 已经完成它的工作时,我需要在每个Request 上发送一个Event,然后我需要修改@987654328 @。

有什么想法吗?

谢谢

【问题讨论】:

  • 您正在寻找一个事件订阅者:symfony.com/doc/current/… 例如,这可以在每个 onKernelRequest 上运行..
  • 我也发现了这个,但是我不知道如何访问EntityManager和Security,因为这些类只接收事件,我错了吗?
  • 发表了一个答案.. 希望你能从那里得到一些工作..

标签: php symfony events filter doctrine


【解决方案1】:

您正在寻找事件订阅者 (Ref)

这是一个示例,您可以使用它来显示对实体管理器和安全类的访问权限。将此文件放在src/EventSubscriber/TenantFilterEventSubscriber.php 中,然后它将在每个请求上运行。

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\Security\Core\Security;
use Doctrine\ORM\EntityManagerInterface;

class TenantFilterEventSubscriber implements EventSubscriberInterface
{
    protected $security;

    public function __construct(Security $security, EntityManagerInterface $entityManager)
    {
        $this->security = $security;
        $this->entityManager = $entityManager;
    }

    public function onKernelController(ControllerEvent $event)
    {
        $controller = $event->getController();

        if (!is_array($controller)) return;

        if ($controller[0] instanceof YourController) {
            $user = $this->security->getUser();

            if (null !== $user) {
                // Do stuff
            }
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            'kernel.controller' => 'onKernelController',
        );
    }
}

【讨论】:

  • 它就像一个魅力,谢谢!
猜你喜欢
  • 2014-07-08
  • 1970-01-01
  • 2012-10-21
  • 2013-03-21
  • 1970-01-01
  • 1970-01-01
  • 2010-12-06
  • 2018-09-28
  • 1970-01-01
相关资源
最近更新 更多