如何使用构造函数将角色添加到组

How to add role to group using constructor

我试过在每个组创建时为他们设置角色。我认为使用 __constructor 会是个好主意,但它不起作用,ROLE_ADMIN 不在新组中。我不知道我做错了什么。

<?php
// src/AppBundle/Entity/Group.php
namespace AppBundle\Entity;

use FOS\UserBundle\Model\Group as BaseGroup;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="AppBundle\Repository\GroupRepository")
 * @ORM\Table(name="d0s_groups")
 */
class Group extends BaseGroup
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @Assert\NotBlank(
     *     message="Nazwa grupy nie może być pusta."
     * )
     * @Assert\Length(
     *      min = 3,
     *      max = 32,
     *      minMessage = "Nazwa grupy musi mieć conajmniej 3 znaki.",
     *      maxMessage = "Nazwa grupy może mieć maksymalnie 32 znaki."
     * )
     */
    protected $name;

    public function __construct($name, $roles = array())
    {
        parent::__construct($name, $roles);
        $this->addRole("ROLE_ADMIN");
    }

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

    public function __toString()
    {
        return $this->getName();
    }
}

文档说得最好:

The constructor of an entity is only ever invoked when you construct a new instance with the new keyword. Doctrine never calls entity constructors, thus you are free to use them as you wish and even have it require arguments of any type.

来源:https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/architecture.html

所以本质上,除非您实际上 store 数据库中的角色,否则当从 db 加载对象时,您的构造函数是无关紧要的。有很多方法可以解决这个问题,您可以覆盖 getRoles 方法以在那里添加额外的角色。