Symfony2 身份验证系统逻辑问题


Symfony2 Authentication system logical issue

我正在尝试编写一个与Symfony本身相结合的授权系统。我的逻辑是这样的:

  1. 有一个User表保存系统用户。
  2. 有一个Role桌子照顾角色。
  3. 有一个Permission表,他保留了网站每个部分的权限。
  4. 有一个User_Role表告诉我们哪个用户是哪个角色。
  5. 有一个Role_Permission表,用于定义每个角色的权限。

我已经在数据库中创建了表及其关系,并将它们导入到Symfony(创建的实体)。

现在的问题是:

/**
* @inheritDoc
*/
public function getRoles()
{
    return array('ROLE_TEST');
}

如何在角色数组中加载每个用户的角色?

public function getRoles()
{
    $roles = array();
    // Checking that the user has permissions attached
    if ($this->getPermissions() !== null)
    {
        // Looping on the permissions
        foreach($this->getPermissions() as $permission)
        {
            // Checking that the permission has roles attached
            if ($permission->getRoles() !== null)
            {
                // Looping on the roles for each permission
                foreach($permission->getRoles() as $role)
                {
                    $roles[] = $role->getName();
                }
            }
        }
    }
    return $roles;
}

更好的解决方案是创建一个UserManager服务,并通过Doctrine Query Builder获取角色(减少对数据库的调用):

/** @var EntityManager $this->em */
$roles = $this->em->createQueryBuilder()
    ->select('r')
    ->from('AcmeBundle:Role', 'r')
    ->innerJoin('r.permissions', 'p')
    ->innerJoin('p.users', 'u')
    ->where('u = :user')
    ->setParameter(':user', $user)
    ->getQuery()
    ->getResult()
;

感谢纪尧姆·韦巴尔,我找到了另一种解决方案。我做了一个视图,只返回用户ID和用户的角色(按视图制作4个表)最后在用户表和user_role(视图)表之间建立逻辑关系。一切都很好。