I'm trying to write a authorization system combining with the Symfony itself. My logic is like this:
User
table who holds the system users.Role
table who take care of roles.Permission
table who keeps the Each part of websites' permission.User_Role
table which tells us which user is is which Role.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?
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()
;
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.