Search code examples
symfonyuser-roles

Symfony2 User Roles (BETA2)


What's the appropriate way to add a user to a role.. for every new user, do I have to do:

$em->getRepository('MyBundle:Role')->findOneBy(array('name' => 'ROLE_USER'))

every time?

I'm not too much of a fan of how large UserBundle is.... and I don't use XML. I'm using YML/Annotations, so the UserBundle is pretty hard to follow for certain things.

So yes, what's the best / cleanest way to do a user signup and associate him to a default role?


Solution

  • The simplest way I've found is just to define roles as a field of type array on your User object. Then, when you're creating the user (on registration or whatnot), it's as simple as

    $roles = array('ROLE_USER');
    $user->setRoles($roles);
    

    I've put together a mockup of my user registration process in this gist. It's not fully functional (I can flesh it out later if needed), but it should get you pointed in the right direction.