Symfony 4 Doctrine,如何从数据库加载用户角色

San*_*ung 4 php doctrine symfony symfony4

Symfony 新手。如何使用 Doctrine 从数据库加载当前登录用户的角色。我有 3 张桌子是这样布置的。

users=> ( user_id, username, password, email)

user_roles=> ( id,user_id,role_id)

roles => (role_id, role_name)

我有每个表的实体及其相应的存储库。

我的 security.yaml 看起来像这样。

security:
encoders:
    App\Entity\User:
        algorithm: bcrypt

providers:
    our_db_provider:
        entity:
            class: App\Entity\User
            property: username
            # if you're using multiple entity managers
            # manager_name: customer

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
#            pattern: ^/
#            http_basic: ~
        provider: our_db_provider
        anonymous: true
        form_login:
            #login_path is GET request used ti display the form
            # needs to be route names(alias) not the path.
            login_path: login

            #check_path is a POST request
            check_path: logincheck
            use_forward: true

            default_target_path: default
            always_use_default_target_path: true
Run Code Online (Sandbox Code Playgroud)

我的Entity/User实现UserInterface组件和通过阅读文档我开始知道该getRoles()方法负责更新用户角色。我创建了一个自定义方法,getUserRoles($id)UserRolesRepository.php其中我设法返回当前用户角色的字符串数组,但是我无法从Entity. 我知道我不应该从 Entity 类访问 Repository 方法,但我深陷在这个阶段。所以现在我的getRoles()方法返回静态数组return array('ROLE_ADMIN', 'ROLE_EDITOR');

我的User实体类

namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use App\Repository\UserRolesRepository;
use Doctrine\ORM\EntityRepository;
use App\Services\Helper;

/**
 * @ORM\Table(name="`user`")
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements UserInterface, \Serializable
{
    /**
    * @ORM\Id()
    * @ORM\GeneratedValue()
    * @ORM\Column(type="integer")
    */
private $id;

/**
 * @ORM\Column(type="string", length=25, nullable=true)
 */
private $username;

/**
 * @ORM\Column(type="string", length=64, nullable=true)
 */
private $password;

/**
 * @ORM\Column(type="string", length=254, nullable=true)
 */
private $email;

/**
 * @ORM\Column(type="boolean", nullable=true)
 */
private $isActive;

private $roles;

/**
 * @ORM\Column(type="string", length=254, nullable=true)
 */
private $role;

public function __construct()
{
    $this->isActive = true;
}

/**
 * @return mixed
 */
public function getRole()
{
    return $this->role;
}

/**
 * @param mixed $role
 */
public function setRole($role)
{
    $this->role = $role;
}

public function getId()
{
    return $this->id;
}

public function getUsername(): ?string
{
    return $this->username;
}

public function setUsername(?string $username): self
{
    $this->username = $username;

    return $this;
}

public function getPassword(): ?string
{
    return $this->password;
}

public function setPassword(?string $password): self
{
    $this->password = $password;

    return $this;
}

public function getEmail(): ?string
{
    return $this->email;
}

public function setEmail(?string $email): self
{
    $this->email = $email;

    return $this;
}

public function getIsActive(): ?bool
{
    return $this->isActive;
}

public function setIsActive(?bool $isActive): self
{
    $this->isActive = $isActive;

    return $this;
}


//return is required or else returns an fatal error.
public function getRoles()
{
    return array('ROLE_ADMIN','ROLE_EDITOR');
}

public function eraseCredentials()
{
    // TODO: Implement eraseCredentials() method.
}

public function serialize()
{
    // TODO: Implement serialize() method.
    return serialize(array(
        $this->id,
        $this->username,
        $this->password,
    ));
}

/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{
    list (
        $this->id,
        $this->username,
        $this->password,
        // see section on salt below
        // $this->salt
        ) = unserialize($serialized, ['allowed_classes' => false]);
}

public function getSalt()
{
    // TODO: Implement getSalt() method.
    return null;
}
}
Run Code Online (Sandbox Code Playgroud)

OK *_*ure 5

到目前为止,您还没有根据您的数据库结构将您的用户映射到角色。

private $roles;
Run Code Online (Sandbox Code Playgroud)

没有关于它如何映射到角色表的信息。它应该看起来像:

/**
 * @var Collection|Role[]
 * @ORM\ManyToMany(targetEntity="Role")
 * @ORM\JoinTable(
 *      name="user_roles",
 *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")}
 * )
 */
private $roles;
Run Code Online (Sandbox Code Playgroud)

您还需要在构造中创建一组初始角色,以便getRoles不会引发错误,并且可以在需要时将角色逐个添加到新用户:

public function __construct()
{
    $this->isActive = true;
    $this->roles = new ArrayCollection();
}
Run Code Online (Sandbox Code Playgroud)

您可以删除getRole()andsetRole()因为我们没有单一角色(除非界面需要),并且您可能会丢失当前$role属性:

/**
 * @ORM\Column(type="string", length=254, nullable=true)
 */
private $role;
Run Code Online (Sandbox Code Playgroud)

但是添加一个带集合的 setter:

public function setRoles(Collection $roles)
{
    $this->roles = $roles;
}
Run Code Online (Sandbox Code Playgroud)

然后获取角色:

public function getRoles()
{
    return $this->roles->toArray();
}
Run Code Online (Sandbox Code Playgroud)

如果您使用表单创建用户(尤其是 Sonata Admin 表单),除了添加和删除用户的单个角色之外,您还可以使用以下方法(它会删除用户和角色之间的关系,而不是删除角色之间的关系)角色本身):

public function addRole(Role $role)
{
    $this->roles->add($role);
}
Run Code Online (Sandbox Code Playgroud)

还有一个删除角色:

public function removeRole(Role $role)
{
    $this->roles->removeElement($role);
}
Run Code Online (Sandbox Code Playgroud)