我从symfony开始,我想创建一个多客户端应用程序。 我希望每次表都有与我公司表的链接时,根据所连接用户的所属公司自动过滤我的SQL查询内容。
我找到了创建过滤器的方法,但我找不到在此过滤器中检索有关已连接用户公司的信息的方法。
我使用FOSuser我用我自己的User类覆盖它。
我的config.yml
#app\config\config.yml
doctrine:
dbal:
...
orm:
auto_generate_proxy_classes: '%kernel.debug%'
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
filters:
company:
class: 'Acme\CompanyBundle\Repository\Filters\CompanyFilter'
enabled: true
我的过滤器
<?php
#src\Acme\CompanyBundle\Repository\Filters\CompanyFilter.php
namespace Acme\CompanyBundle\Repository\Filters;
use Doctrine\ORM\Mapping\ClassMetaData;
use Doctrine\ORM\Query\Filter\SQLFilter;
use Acme\UserBundle\Entity\UserEntity;
use Acme\CompanyBundle\Entity\CompanyEntity;
class CompanyFilter extends SQLFilter
{
public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
{
if ($targetEntity->hasAssociation("company")) {
// here how to get the connected user ???
$company = $user->getCompany();
$idCompany = $company->getId();
return $targetTableAlias . ".company_id = '".$idCompany."'";
}
return "";
}
}
提前感谢您的帮助
答案 0 :(得分:4)
设置onKernelRequest侦听器,将令牌存储服务传递给它,以便将用户定义为SQLFilter的参数。
所以在你的services.yml中添加:
services:
on_request_listener:
class: Acme\CompanyBundle\EventListener\OnRequestListener
arguments: ["@doctrine.orm.entity_manager", "@security.token_storage"]
tags:
-
name: kernel.event_listener
event: kernel.request
method: onKernelRequest
创建监听器:
class OnRequestListener
{
protected $em;
protected $tokenStorage;
public function __construct($em, $tokenStorage)
{
$this->em = $em;
$this->tokenStorage = $tokenStorage;
}
public function onKernelRequest(GetResponseEvent $event)
{
if($this->tokenStorage->getToken()) {
$user = $this->tokenStorage->getToken()->getUser();
$filter = $this->em->getFilters()->enable('company');
$filter->setParameter('user', $user);
}
}
}
然后最后你的SQLFilter:
<?php
#src\Acme\CompanyBundle\Repository\Filters\CompanyFilter.php
namespace Acme\CompanyBundle\Repository\Filters;
use Doctrine\ORM\Mapping\ClassMetaData;
use Doctrine\ORM\Query\Filter\SQLFilter;
use Acme\UserBundle\Entity\UserEntity;
use Acme\CompanyBundle\Entity\CompanyEntity;
class CompanyFilter extends SQLFilter
{
public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
{
if ($targetEntity->hasAssociation("company") && $this->hasParameter('user')) {
$user = $this->getParameter('user');
$company = $user->getCompany();
$idCompany = $company->getId();
return $targetTableAlias . ".company_id = '".$idCompany."'";
}
return "";
}
}