簡體   English   中英

Symfony 4:原則實體基於ROLE_ *返回不同的數據

[英]Symfony 4: Doctrine-entity returns different data based on ROLE_*

我有一個Account -entity,該實體應根據當前登錄用戶的角色返回不同的數據:

return [                                     // to be returned if user has role:
    'id' => $this->id,                       // ROLE_USER, ROLE_PAYED, ROLE_ADMIN
    'name' => $this->name,                   // ROLE_USER, ROLE_PAYED, ROLE_ADMIN
    'hobbies' => ['some', 'tags'],           // ROLE_PAYED, ROLE_ADMIN
    'roles' => ['ROLE_USER', 'ROLE_PAYED']   // ROLE_ADMIN
];

如果我要在Controller內進行此更改,我可以簡單地稱為選民 但是我想在實體的jsonSerialize使用它,以便在每個請求中均無例外地實現它。

我猜真正的問題是“如何在實體中獲得選民”,但實際上我對Symfony的了解還不夠(現在僅使用10天)。

選民是服務,服務實際上不應該在實體內部。 實體不應該對視圖或控制器中的任何內容有任何了解。 如果您發現自己需要在實體內部提供服務,則通常表明您需要重新考慮體系結構。

我要采取的方法是創建一個JsonSerializeAccount服務,該服務使用AuthorizationChecker創建json數組。

<?php

namespace App\Service;

use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use App\Entity\Account;

class JsonSerializeAccount {
    /**
     * @var AuthorizationCheckerInterface
     */
    private $authorizationChecker;

    public function __construct(AuthorizationCheckerInterface $authorizationChecker)
    {
        $this->authorizationChecker = $authorizationChecker;
    }

    public function jsonSerialize(Account $account): array
    {
        $json = [
            'id' => $account->getId(),
            'name' => $account->getName(),
        ];

        if ($this->authorizationChecker->isGranted('view_hobbies', $account)) {
            $json['hobbies'] = $account->getHobbies();
        }

        if ($this->authorizationChecker->isGranted('view_roles', $account)) {
            $json['roles'] = $account->getRoles();
        }

        return $json;
    }
}

暫無
暫無

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

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