我想将 Symfony 5 设置为使用“人类可读”角色进行显示。在 TWIG 中显示用户信息时,我可以使用 {{ user.roles[0] }}。但是,这显示(例如)“ROLE_ACCOUNTADMIN”(针对数据库中的用户保存),但我希望它显示为“Account Administrator”。在使用 user_roles 表的 Symfony 3 中,有一个“角色”和一个“名称”字段,但这已被删除。是否可以在 Symfony 5 中完成此操作而无需在我想使用它时定义/包含数组?
你可以创建一个扩展树枝,你有很多解决方案......, 但是对于我看到的最简单的解决方案,只需在实体上放置一个字段并使用主要角色对其进行初始化,这样您就可以在 api 和 twig 上获得信息,邮寄...
<?php
namespace App\Entity;
// ...
class User
{
public static $USER_ROLE_AS_HUMAN_READABLE_INDEX = [
'ROLE_ACCOUNTADMIN' => 'Account Administrator',
'OTHER_ROLE' => 'Description',
// ...
]
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
// without mapping ..
private $roleHumanReadable
// ...
public function __construct() {
$this->initializeRoleHumanReadable();
}
public function getRoleHumanReadable():?string
{
return $this->roleHumanReadable;
}
public function initializeRoleHumanReadable():void
{
$rolePrincipal = $this->getRoles()[0] ?? null;
if (!isset(static::$USER_ROLE_AS_HUMAN_READABLE_INDEX[$rolePrincipal])) {
return;
}
$this->roleHumanReadable = static::$USER_ROLE_AS_HUMAN_READABLE_INDEX[$rolePrincipal];
}
}
实体类似乎是放置角色列表的合理位置,但我不会为这样一个简单的功能添加任何构造函数。我的看起来更像这样。
namespace App\Entity;
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
public const ROLE_NAMES = [
'ROLE_USER' => 'User',
'ROLE_ADMIN' => 'Administrator',
];
public function getPrettyRoles(): array
{
$all_roles = array_flip(self::ROLE_NAMES);
$these_roles = $this->getRoles();
return array_keys(array_intersect($all_roles, $these_roles));
}
}