Php 将setter与数组一起使用

Php 将setter与数组一起使用,php,arrays,forms,symfony,Php,Arrays,Forms,Symfony,我的问题是:我正在开发我的网站的安全性。在我的用户注册表中,我有五个字段:1)姓名2)电子邮件3)密码4)活动5)角色。显然,我不希望表单中的最后两项可见,否则会违反我的安全预期 因此,我将“isActive”项与setter放在一起,但是角色是一个数组,如果我得到以下内容:$user->setRoles('role\u user')不起作用 我得到了这个错误: ContextErrorException:可捕获致命错误:参数1传递给 条令\Common\Collections\ArrayCol

我的问题是:我正在开发我的网站的安全性。在我的用户注册表中,我有五个字段:1)姓名2)电子邮件3)密码4)活动5)角色。显然,我不希望表单中的最后两项可见,否则会违反我的安全预期

因此,我将“isActive”项与setter放在一起,但是角色是一个数组,如果我得到以下内容:
$user->setRoles('role\u user')
不起作用

我得到了这个错误:

ContextErrorException:可捕获致命错误:参数1传递给 条令\Common\Collections\ArrayCollection::\uuu construct()必须为 在中调用的类型数组(给定字符串) C:\xampp\htdocs\Lavoc\vendor\doctor\orm\lib\doctor\orm\UnitOfWork.php 第547行,并在中定义 C:\xampp\htdocs\Lavoc\vendor\doctor\collections\lib\doctor\Common\collections\ArrayCollection.php 第47行

这是我的密码:

 public function registroAction()
{
    $peticion = $this->getRequest();
    $em = $this->getDoctrine()->getManager();
    $user = new User();
    $role = new Role();
    $role->addRole(array('ROLE_USER')); //it does not work
    $user->setRoles($role);  // User relate with Role
    $formulario = $this->createForm(new UserType(), $user);


    if ($peticion->getMethod() == 'POST') 
    {
        $formulario->submit($peticion);

        if ($formulario->isValid()) {
        $encoder = $this->get('security.encoder_factory')->getEncoder($user);
        $user->setSalt(md5(time()));
        $passwordCodificado = $encoder->encodePassword($user->getPassword(), $user->getSalt() );
        $user->setPassword($passwordCodificado);

        $em = $this->getDoctrine()->getManager();

        $em->persist($user);
        $em->flush();
        return $this->redirect($this->generateUrl('usuario_registro'));
        }
    }

    return $this->render( 'ProyectoSeguridadBundle:Seguridad:registro.html.twig',
    array('formulario' => $formulario->createView())
    );
}
这是我的用户模型:

    <?php

namespace Proyecto\SeguridadBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Proyecto\SeguridadBundle\Entity\User
*
* @ORM\Table(name="lavoc_users")
* @ORM\Entity(repositoryClass="Proyecto\SeguridadBundle\Entity\UserRepository")
*/
class User implements AdvancedUserInterface
{
    /**
    * @var integer
    *
    * @ORM\Column(name="id", type="integer")
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    */
    private $id;


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


    /**
    * @var string
    *
    * @ORM\Column(name="salt", type="string", length=32)
    */
    private $salt;


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


    /**
    * @var string
    *
    * @ORM\Column(name="email", type="string", length=60, unique=true)
    */
    private $email;


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



    /**
    * @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
    *
    */
    private $roles;



    public function __construct()
    {
        $this->roles = new ArrayCollection();
        $this->isActive = true;
        $this->salt = md5(uniqid(null, true));

    }


    /**
    * Get id
    *
    * @return integer
    */
    public function getId()
    {
        return $this->id;
    }


    /**
    * Set username
    *
    * @param string $username
    * @return User
    */
    public function setUsername($username)
    {
        $this->username = $username;
        return $this;
    }


    /**
    * @inheritDoc
    */
    public function getUsername()
    {
        return $this->username;
    }


    /**
    * Set salt
    *
    * @param string $salt
    * @return User
    */
    public function setSalt($salt)
    {
        $this->salt = $salt;
        return $this;
    }


    /**
    * @inheritDoc
    */
    public function getSalt()
    {
        return $this->salt;
    }


    /**
    * Set password
    *
    * @param string $password
    * @return User
    */
    public function setPassword($password)
    {
        $this->password = $password;
        return $this;
    }


    /**
    * @inheritDoc
    */
    public function getPassword()
    {
        return $this->password;
    }


    /**
    * Set email
    *
    * @param string $email
    * @return User
    */
    public function setEmail($email)
    {
        $this->email = $email;
        return $this;
    }


    /**
    * Get email
    *
    * @return string
    */
    public function getEmail()
    {
        return $this->email;
    }


    /**
    * Set isActive
    *
    * @param boolean $isActive
    * @return User
    */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;
        return $this;
    }


    /**
    * Get isActive
    *
    * @return boolean
    */
    public function getIsActive()
    {
        return $this->isActive;
    }


    /**
    * @inheritDoc
    */
    public function getRoles()
    {

        $roles = array();
        foreach ($this->roles as $role) {
            $roles[] = $role->getRole();
        }

        return $roles;
    }


    /**
    * @inheritDoc
    */
    public function eraseCredentials() {
    }


    /**
    * @see \Serializable::serialize()
    */
    public function serialize() {
        return serialize(array($this->id,));
    }


    /**
    * @see \Serializable::unserialize()
    */
    public function unserialize($serialized) {
        list ($this->id,) = unserialize($serialized);
    }


    public function isAccountNonExpired() {
        return true;
    }


    public function isAccountNonLocked() {
        return true;
    }


    public function isCredentialsNonExpired() {
        return true;
    }


    public function isEnabled() {
        return $this->isActive;
    }


    /**
    * Set roles
    *
    * @param string $roles
    * @return User
    */
    public function setRoles($roles)
    {
        $this->roles = $roles;
        return $this;
    }


}

在这一行
$user->setRoles('ROLE\u user')
中,您尝试将
字符串添加到
数组集合中。这就是为什么会出现
ArrayCollection
异常

您能否尝试添加此代码(请确保用您自己的
角色
模型替换
\MyBundle\Entity\Role

要使用它,需要将
Role
对象传递给
addRole
removole
方法

其他信息

如果要为
isActive
和/或其他值定义默认值,可以在
用户
模型的
构造函数
中调用相应的setter

例如:

public function __construct()
{
    // your own logic
    $this->isActive = true;
}

希望能有所帮助。

角色是ArrayCollection,因此不能用字符串替换它

您应该添加这样一个函数

public function addRoles($role)
{
    $this->roles[] = $role;
    return $this
}

使用addRole()代替setRoles()

您需要创建
addRole(Role$Role)
方法

或通过检查角色是否存在:

public function addRole(Role $role)
{ 
    if (!$this->roles->contains($role)) {
        $this->roles->add($role);
    }
}

您好,这样看来,您提出我并在我的代码中实现它是非常合乎逻辑的。setter isActive运行良好,成功地为我提供了真实的isActive。但是我得到了一个关于这些角色的错误:ContextErrorException:警告:spl_object_hash()希望参数1是object,字符串以C:\xampp\htdocs\Lavoc\vendor\doctor\orm\lib\doctor\orm\UnitOfWork.php第1375行给出,您能给我们看一下
用户
模型的代码吗?请修改问题我实施了您提出的内容,但与驱动程序的角色是角色用户不同。你能帮我吗?我实现了你给我提的东西,但不像在司机的角色是角色用户中那样。你能帮个忙吗?在另一个答案的代码中,他们用你的实体“\MyBundle\entity\Role”键入参数,这意味着你必须向这个addRoles()函数传递一个Role对象,因此,您必须获取ROLE_USER的实体,然后将其添加到您的ArrayCollection中。我实现了您提出的内容,但与驱动程序的ROLE_USER不同。你能帮我吗?我不明白你的评论。你能更新你问题中的代码和你得到的错误吗?
public function addRoles($role)
{
    $this->roles[] = $role;
    return $this
}
public function addRole(Role $role)
{ 
    $this->roles->add($role);
}
public function addRole(Role $role)
{ 
    if (!$this->roles->contains($role)) {
        $this->roles->add($role);
    }
}