0

I'm trying to write a authorization system combining with the Symfony itself. My logic is like this:

  1. there is a User table who holds the system users.
  2. there is a Role table who take care of roles.
  3. there is a Permission table who keeps the Each part of websites' permission.
  4. there is a User_Role table which tells us which user is is which Role.
  5. there is a Role_Permission table which define Each Role's permission.

I have created the tables in the database and their relationships. and imported them to Symfony ( created entity ).

and now the problem is:

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

How can I load each user's roles in the roles array?

2 Answers 2

1
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;
}

Better solution is to create a UserManager Service and to get the roles via the Doctrine Query Builder (Less calls to the database):

/** @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()
;
Sign up to request clarification or add additional context in comments.

Comments

0

Thanks to Guillaume Verbal, I found another solution for that. I made a view which just return User id and roles of the users ( make 4 tables one by view ) and finally make a logical relationship between user and user_role(view) tables. everything just work fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.