symfony 在哪里以及如何存储用户角色

Where and how symfony store user roles

大家好,我想了解 symfony 中关于用户和用户角色的逻辑及其工作原理。我是 symfony 的新手,我遵循本教程: http://symfony.com/doc/current/security/entity_provider.html

在我的项目中一切正常,但是当我查看数据库时,我有 user table 和所有用户我在 table.

中注册的数据

但是 table 用户角色在哪里? symfony 如何知道谁是 ROLE_ADMIN 和谁是 ROLE_MODERATOR。如何实现所有具有特定角色的用户并将该角色保存在数据库中,以便稍后可以从某些管理面板更改它? ACL 我是?

Symfony 不负责存储您的角色。如果您需要管理它们,则必须存储它们,例如抛出一个管理控制台。

您的用户实体实现的 Symfony\Component\Security\Core\User\UserInterface 接口包含一个方法名称 getRoles 应该 return 代表用户的 String 数组Symfony\Component\Security\Core\Role\RoleInterface 的角色或和数组。因此,您可以在名为 Role 的项目中创建一个实现 Symfony\Component\Security\Core\Role\RoleInterface 的实体。然后 link 该实体向您的用户实体抛出一个 ManyToMany 关联。最后实现 getRoles 方法,该方法应该 return 给定用户的角色。

然后您可以像管理项目中的任何其他实体一样管理您的角色。

RoleInterface 现已弃用,并将在 4.0 中删除,因此您可以像 Genoud Magloire 所说的那样做,但一定要 extend Symfony\Component\Security\Core\Role\Role

这是我的角色实体的示例。

<?php

namespace ExampleCoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * ExampleRole
 *
 * @ORM\Table(name="EXAMPLE_ROLE")
 * @ORM\Entity
 */
class ExampleRole extends Role
{
    /**
     * @var integer
     *
     * @ORM\Column(name="ID", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     */
    private $id;

    /**
     * @var string
     *
     * @Assert\NotBlank()
     * @Assert\Length(
     *      min = 9,
     *      max = 100,
     *      minMessage = "Role name must be at least {{ limit }} characters long",
     *      maxMessage = "Role name cannot be longer than {{ limit }} characters"
     * )
     * @ORM\Column(name="ROLE_NAME", type="string", length=255, nullable=false, unique=true)
     *
     */
    private $roleName;

    /**
     * @var string
     *
     * @Assert\NotBlank()
     * @Assert\Choice({"Y","N"})
     *
     * @ORM\Column(name="GRANTABLE", type="string", length=1, nullable=false)
     */
    private $grantable;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="CREATED_ON", type="datetime", nullable=false)
     */
    private $createdOn;

    //...and so on with whatever else you want to save. 

    public function __construct( $roleName = null )
    {
        parent::__construct( $roleName );
    }