Symfony 2 - Loading roles from database

前端 未结 2 1787
迷失自我
迷失自我 2021-02-06 13:05

My roles are stored in the database and I am trying to load them dynamically upon login. What I\'m doing is querying for the roles and setting them on the user object in my user

相关标签:
2条回答
  • 2021-02-06 13:13

    It looks like you may not be aware of the built in role management that Symfony offers. Read the docs - Managing roles in the database It is actually quite simple to do what you want, all you need to do is implement an interface and define your necessary function. The docs I linked to provide great examples. Take a look.

    UPDATE

    It looks like the docs don't give you the use statement for the AdvancedUserInterface. Here it is:

    // in your user entity
    use Symfony\Component\Security\Core\User\AdvancedUserInterface;
    

    then in your role entity:

    use Symfony\Component\Security\Core\Role\RoleInterface;
    

    The docs show you how to do the rest.

    UPDATE

    Take a look at this blog post, which shows how to create roles dynamically:

    Dynamically create roles

    0 讨论(0)
  • 2021-02-06 13:30

    The problem here stemmed from the fact that I thought I was implementing

    Symfony\Component\Security\Core\User\EquatableInterface;
    

    but wasn't (as you can see in the original question, I forgot to add it to my class definition). I'm leaving this here for people if they come across it. All you need is to implement this interface, and add the following method to your user entity.

    public function isEqualTo(UserInterface $user) {
        if ($user instanceof User) {
        // Check that the roles are the same, in any order
            $isEqual = count($this->getRoles()) == count($user->getRoles());
            if ($isEqual) {
                foreach($this->getRoles() as $role) {
                    $isEqual = $isEqual && in_array($role, $user->getRoles());
                }
            }
            return $isEqual;
        }
    
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题