9

I'm currently trying to figure out the best way to implement doctrine persisted Role entities as a M2M relationship compatible with FOSUserBundle. Previously I was using just strings with the default implementation and was persisting it with a doctrine array mapping.

Now I need to have roles as seperate entites as we want to build an admin backend where others can grant users roles.

Basically, it's a pain in the ass. The FOS interfaces are built for string representations, not Role entities. Change the implementation, you break a lot of stuff i.e. FOS commands to promote users. And it's hard to figure out exactly which pieces of the interfaces are needed to allow the symfony2 security system to continue working correctly.

I could rewrite the role management code and use Role entities as much as possible, e.g.:

$user->addRole(new Role('ROLE_FOO'));

But that breaks commands and possibly existing code?

Or continue using:

$user->addRole('ROLE_FOO');

And couple role/entity manager code in addRole() (bad design).

I've noticed this is a grey area (Role entities with FOS) and has been mentioned on the symfony2 boards and round here, but no decent solutions.

Anyone had any experience or can think of a decent solution?

Mohammed H
  • 6,880
  • 16
  • 81
  • 127
jmoz
  • 7,846
  • 5
  • 31
  • 33
  • 1
    If the commands use the object's interface to set those values, just overriding the getRoles() and setRoles() calls to preserve the old behavior might be sufficient. – Louis-Philippe Huberdeau Dec 05 '11 at 16:09
  • The commands use addRole(string) so then there would be a mix of strings and entities (not keen on). And also the setRoles(array) is another issue as the interface typehints an array, not array collection. Could get round the commands buy writing my own. – jmoz Dec 05 '11 at 16:23
  • 2
    Maybe you could implement `__toString` in the Role entity and fork FOSUserBundle to cast to string when necessary... – greg0ire Dec 05 '11 at 22:01

1 Answers1

12

I decided to go with a mix of an array/ArrayCollection implementation. I tried to follow the existing interfaces as much as possible so as not to break the security system. I have documented my solution at http://blog.jmoz.co.uk/symfony2-fosuserbundle-role-entities

jmoz
  • 7,846
  • 5
  • 31
  • 33