Shrujan Shetty
Shrujan Shetty

Reputation: 2392

Issues related to roles in symfony

My project has many roles: admin, HR, manager, employee. How do I implement it in a generalized way in Symfony2 such that new roles can be added in future?

Upvotes: 0

Views: 608

Answers (1)

Florian Klein
Florian Klein

Reputation: 8915

Symfony2 represents authenticated users using The UserInterface interface.

This interface asks you to implement the getRoles method, which returns all the roles a user has.

Based on how you implement this UserInterface, you can grab these roles from a database, a web service, or whatever you want.

One simple way to provide these users is the in-memory provider:

# app/config/security.yml
security:
    # ...
    providers:
        in_memory:
            users:
                ryan:  { password: bb87a29949f3a1ee0559f8a57357487151281386, roles: 'ROLE_USER' }
                admin: { password: 74913f5cd5f61ec0bcfdb775414c2fb3d161b620, roles: [ 'ROLE_ADMIN', 'ROLE_RH'] }

Another way is to use the EntityProvider. For more details look at this cookbook entry.

In this last example, user roles are statically stored in a harcoded array, but they could come from another table, using table associations. That's how it's done in the FOSUserBundle.

You can even define a role hierarchy:

# app/config/security.yml
security:
    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

So that any user that has role ROLE_ADMIN has also inherited the role ROLE_USER.

For more info look at the docs.

Upvotes: 2

Related Questions