选民是服务,服务真的不应该在实体内部。实体不应了解视图或控制器中的任何内容。如果您发现自己需要实体内部的服务,这通常是您需要重新思考架构的标志。
我会采取的方法是创建一个
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;
}
}