4

I'm currently working on a Symfony2 project. It is based on Sonata and uses SonataUserBundle/FOSUserBundle for managing users. The initial development has been badly done and I'm in the process of refactoring a lot of it.

The application defines three level of users:

  • Administrators
  • Consultants
  • Businesses

Those are defined as Groups with FOSUserBundle and have a bunch of roles attached to them.

Now everywhere in the code, the previous developers have used (hardcoded) the database IDs of the groups to make cases like this:

$userGroup = $em->getRepository('ApplicationSonataUserBundle:Group')->findOneByName($group_name);
$userGroupId = $userGroup->getId();

if ($userGroupId == 1) {
   // Administrator case
   ...
} else if ($userGroupId == 7) {
   // Consultant case
   ...
}

This is obviously very bad.

My problem is that I'm sure how I can refactor this in a good fashion.
I see three possible way of doing so:

  1. Work directly with the roles defined: ROLE_ADMIN, ROLE_CONSULTANT, ROLE_BUSINESS;

  2. Still use the groups but have some constants with the group name to avoid repeating them all over the place;

  3. Use a multi-user system on top of FOSUserBundle. I quickly reviewed RollerworksMultiUserBundle and PUGXMultiUserBundle. Although I don't know if this is not a bit overhead as my users actually share the same information.

If you guys can point me in the right direction, it would be much appreciated. Maybe there is a complete other way to achieve this properly.

Didier Ghys
  • 30,396
  • 9
  • 75
  • 81

1 Answers1

5

My advice is to use roles directly, and stop using the FOSUserBundle groups entirely. Most of the time, they are useless. Groups are a concept inherited from the symfony1 sfGuardPlugin at a time when the role hierarchy was not yet available in Symfony 2 (way before the stable release). In most cases, the role hierarchy is enough to achieve the need, making groups more complex for no benefit. And for the few other cases, I found that using voters related to actual business logic of the project is more maintainable than using FOSUserBundle groups (I think I haven't used them in any project since 4 years).

Disclaimer: I am the main maintainer of FOSUserBundle.

  • Well, this is what I have been finally doing actually. It didn't seem relevant to use FOSUserBundle groups as we had the same hierarchy defined with Symfony roles. I've discovered about the voters indeed which helped me a lot to easily setup some checks business-wise. Thanks ! – Didier Ghys Jan 04 '16 at 15:01