6

Which properties (and why) should be included in serialize() and deserialize() methods in Symfony 2?

For now i've the id field and it just works, but i'd like to know why and what's the purpose of serialize() in User class. in order to avoid this message:

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.

Class User implements AdvancedUserInterface, \Serializable
{
    /**
     * @return string
     */
    public function serialize()
    {
      return serialize($this->id);
    }

    /**
     * @param string $data
     */
    public function unserialize($data)
    {
      $this->id = unserialize($data);
    }
}

While without implementing \Serializable and with all properties protected, i'm getting:

Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::serialize() must return a string or NULL.

0

1 Answer 1

4

You need to serialize/deserialize the username and the fields you use in the equality check. You don't need to serialize the id property unless it can be changed in your app.

3
  • Thanks for helping. However without serializing the id (e.g. only the username) i'm getting "You cannot refresh a user from the EntityUserProvider that does not contain an identifier."...
    – gremo
    Jul 18, 2012 at 7:54
  • Okay. That's Doctrine specific then. You should serialize it in this case. Jul 18, 2012 at 11:31
  • You definately need id, if you are not going to overwrite the way user object is refreshed. There are few sentences in SF2 documentation on this subject : "The id is the most important value that needs to be serialized because the refreshUser() method reloads the user on each request by using the id. In practice, this means that the User object is reloaded from the database on each request using the id from the serialized object. This makes sure all of the User's data is fresh." Jun 8, 2014 at 22:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.