这个问题的解决方法很简单。User
与您和Role
对象的循环引用相关的所有问题。所以你不必序列化User::$roles
和Role::$users
字段。
看Symfony\Component\Security\Core\Authentication\Token\AbstractToken::__construct()
和Symfony\Component\Security\Core\Authentication\Token\AbstractToken::serialize()
。
你怎么看,Symfony 通过UserInterface::getRoles()
在序列化之前调用来扮演你用户的角色。User
并分别序列化Roles
。
您必须在和实体中实现\Serializable
接口。User
Role
例子:
/**
* Acme\Bundle\UserBundle\Entity\User
*
* @ORM\Table(name="`user`")
* @ORM\Entity(repositoryClass="Acme\Bundle\UserBundle\Entity\UserRepository")
*/
class User implements AdvancedUserInterface, EquatableInterface, \Serializable
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string $username
*
* @ORM\Column(type="string", length=30, unique=true)
*/
private $username;
/**
* @var string $email
*
* @ORM\Column(type="string", length=100, unique=true)
*/
private $email;
/**
* @var string $salt
*
* @ORM\Column(type="string", length=40)
*/
private $salt;
/**
* @var string $password
*
* @ORM\Column(type="string", length=128)
*/
private $password;
/**
* @var boolean $isActive
*
* @ORM\Column(type="boolean")
*/
private $isActive;
/**
* User's roles. (Owning Side)
*
* @var ArrayCollection
*
* @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*/
private $roles;
// .....
/**
* @see \Serializable::serialize()
*/
public function serialize()
{
/*
* ! Don't serialize $roles field !
*/
return \serialize(array(
$this->id,
$this->username,
$this->email,
$this->salt,
$this->password,
$this->isActive
));
}
/**
* @see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->email,
$this->salt,
$this->password,
$this->isActive
) = \unserialize($serialized);
}
}
/**
* Acme\Bundle\UserBundle\Entity\Role
*
* @ORM\Table(name="role")
* @ORM\Entity
*
*/
class Role implements RoleInterface, \Serializable
{
/**
* @var integer $id
*
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string $role
*
* @ORM\Column(name="role", type="string", length=20, unique=true)
*/
private $role;
/**
* Users in group (Inverse Side)
*
* @var ArrayCollection
*
* @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
// .....
/**
* @see \Serializable::serialize()
*/
public function serialize()
{
/*
* ! Don't serialize $users field !
*/
return \serialize(array(
$this->id,
$this->role
));
}
/**
* @see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list(
$this->id,
$this->role
) = \unserialize($serialized);
}
}
并且所有内容都将正确序列化/反序列化。
请参阅https://github.com/symfony/symfony/issues/3691上的铁饼
另见:
http ://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/entities-in-session.html#serializing-entity-into-the-session