Reputation: 3249
My User
entity implements UserInterface
and therefore provides the getRoles()
method. In my system a User
can belong to multiple Group
s. A group can have multiple roles. Thus a user's roles can be determined by collecting all groups and merging the lists of those groups' roles. The same thing is possible with FOSUserBundle.
The easiest algorithm would be:
public function getRoles()
{
$roles = $this->roles;
foreach ($this->getGroups() as $group) {
$roles = array_merge($roles, $group->getRoles());
}
return array_unique($roles);
}
I think this solution is problematic because it will scale badly. For each group a new query has to be executed, so the amount of queries depends on the amount of groups.
Usually I'd solve this by defining a single query which collects all groups of the user and joins the groups' roles. That would require calling the UserRepository
(or directly building a Doctrine query) from the User
entity and I believe that is a bad practice.
So how could I avoid this bad practice while maintaining the performance advantages of a single join query?
(This time it was very hard for me to find a question title that fits. I'm not sure whether there are other simililar situations but I don't think so, because usually I would provide such method in the repository itself. In this case the UserInterface
requires it to be in the entity)
Upvotes: 2
Views: 639
Reputation: 602
The easiest way to do this is to create a custom UserProvider.
see http://symfony.com/doc/current/security/custom_provider.html#create-a-user-provider for the documentations.
Inside this user provider you have to make your query to select the user from an username and add a join to the group entity, so you only have one query
Upvotes: 1