簡體   English   中英

Symfony2-創建一個Doctrine過濾器以選擇當前用戶數據

[英]Symfony2 - Create a Doctrine filter to select current user data

我正在使用Symfony 2構建一個Saas / Multitenant應用程序。我已經創建了一個Doctrine事件訂閱者來添加和更新行的所有者,創建行的用戶,修改行的用戶,時間戳等等。

現在,我需要實現某種過濾器,以便用戶登錄后,他只能看到其公司的數據。 我的第一個操作雖然使用了Doctrine preLoad事件,但是該事件不存在……據我所知,我必須使用Doctrine過濾器,不是嗎? 如果是這樣,此過濾器如何訪問用戶數據以讀取公司ID? 我必須使用依賴注入來注入它嗎? 有什么標准方法可以實現我的目標?

更新我正在尋找的是創建某種Doctrine插件/掛鈎,因此每次我調用從數據庫中獲取數據的任何函數(find,findOneBy等)時,我正在獲取的實體都實現了特定的接口,額外的“ AND company_id =:id” SQL序列被添加到生成的查詢中,因此控制器或模型都不會從其他公司接收數據。

為此,您可以使用官方文檔Doctrine2 SQL過濾器中的DoctrineFilter鏈接

namespace Rwmt\Bundle\RwmtBundle\DoctrineFilters;

use Doctrine\ORM\Mapping\ClassMetaData,
    Doctrine\ORM\Query\Filter\SQLFilter;

class MultiTenantFilter extends SQLFilter
{
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
    {
        // Check if the entity implements the MultiTenant interface
        if (!$targetEntity->reflClass->implementsInterface('Rwmt\Bundle\RwmtBundle\Entity\MultiTenant')) {
            return "";
        }

        return $targetTableAlias.'.tenant_id = ' . $this->getParameter('tenantId');
    }
}

並設置過濾器中使用的參數tenantId,您必須啟用過濾器並設置參數

$filter = $em->getFilters()->enable('multi_tenant');
$filter->setParameter('tenantId', $tenant->getId(), 'integer');

至於MultiTenant接口只是實體要實現的東西

namespace Rwmt\Bundle\RwmtBundle\Entity;
use Rwmt\Bundle\RwmtBundle\Entity\Tenant;

interface MultiTenant
{
    public function setTenant(Tenant $tenant);
    public function getTenant();
}

在Doctrine2中進行過濾很簡單。 只需為變量分配過濾器函數,然后通過ArrayCollection類中包含的filter()方法將該變量作為參數發送。

$closure = function($list_item) use($user) {                                
        return $list_item->belongsToSameCompanyThatEmploys($user) === true;
};                                                         
$filtered_array_collection = $arrayYouWantToFilter->filter($closure); 

在此示例中,您必須先前已在list_item的類中定義了一個方法belongsToSameCompanyThatEmploys($user) ,如果該方法屬於用戶所在的公司,則該方法返回true

UPDATE您還需要指出過濾器函數應使用局部變量user,因為由於具有自己的作用域,否則不會使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM