Symfony 2 - Loading roles from database

前端 未结 2 1790
迷失自我
迷失自我 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: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;
    }
    

提交回复
热议问题