我无法使用'员工'在symfony2中进行身份验证。实体,因为它包含许多与我的项目中的其他实体的映射。我的一些映射如下:
/**
* @var EmployeeDesignation
*
* @ORM\ManyToOne(targetEntity="EmployeeDesignation")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="employee_designation_id", referencedColumnName="id")
* })
*/
private $employeeDesignation;
/**
* @var EmployeeDesignation
*
* @ORM\ManyToOne(targetEntity="EmployeeType")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="employee_type_id", referencedColumnName="id")
* })
*/
private $employeeType;
身份验证无需任何映射即可正常工作我试过了' Serialize()'和' Unserialize()'其中的方法如下:
class Employee implements AdvancedUserInterface, \Serializable{
/**
* serialize the username
* @return serialize
*/
public function serialize() {
return serialize($this->emailOfficial);
}
/**
* unserialize
* @param $data
*/
public function unserialize($data) {
$this->em = unserialize($data);
}
执行上述方法后,我收到以下错误:
You cannot refresh a user from the EntityUserProvider that does not contain an identifier. The user object has to be serialized with its own identifier mapped by Doctrine.
我试过这种方式以摆脱之前的错误,如下所示:
Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::serialize() must return a string or NULL
那么,任何人都可以建议一种克服这个问题的方法吗?
答案 0 :(得分:19)
我遇到过类似的事情,经过一番研究,我尝试过和你一样的事情。
但在某些时候,我发现通过设置__sleep
方法,每件事都运行良好。
class User implements PlayerInterface { /** * @var integer $id * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; ... public function __sleep() { return array('id'); } ...
@ORM\Id
的字段是返回数组的一部分。我不知道为什么它在设置新关联时会导致这种情况(我的是ManyToMany),但它可能来自这个地方:
// see Symfony\Component\Security\Http\Firewall\ContextListener::onKernelResponse() ... $event->getRequest() ->getSession() ->set('_security_'.$this->contextKey, serialize($token)); ...
希望这可以帮助某人。
修改强>
参考文献:
答案 1 :(得分:2)
对我来说这只有效:
class User implements UserInterface
到
class User implements UserInterface, \Serializable
我需要将以下方法添加到User
类:
public function serialize() {
return serialize($this->username);
}
public function unserialize($data) {
$this->username = unserialize($data);
}
答案 2 :(得分:1)
还有另一种可能性来解决这个问题。您必须将与您的用户关联的实体的所有属性的可见性设置为“受保护”
请参阅:http://www.metod.si/symfony2-error-usernamepasswordtokenserialize-must-return-a-string-or-null/
答案 3 :(得分:0)
您应该在用户类的每个变量中加上“protected”。至少对我而言,工作:)