Skip to content

Commit 5547d66

Browse files
committed
[symfony#1874] Tweaking the entity provider article, including a new explanation of why serialization might be important
1 parent 2001174 commit 5547d66

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

cookbook/security/entity_provider.rst

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ focus on the most important methods that come from the
5454
* @ORM\Table(name="acme_users")
5555
* @ORM\Entity(repositoryClass="Acme\UserBundle\Entity\UserRepository")
5656
*/
57-
class User implements UserInterface
57+
class User implements UserInterface, \Serializable
5858
{
5959
/**
6060
* @ORM\Column(type="integer")
@@ -140,6 +140,26 @@ focus on the most important methods that come from the
140140
{
141141
return $this->username === $user->getUsername();
142142
}
143+
144+
/**
145+
* @see \Serializable::serialize()
146+
*/
147+
public function serialize()
148+
{
149+
return serialize(array(
150+
$this->id,
151+
));
152+
}
153+
154+
/**
155+
* @see \Serializable::unserialize()
156+
*/
157+
public function unserialize($serialized)
158+
{
159+
list (
160+
$this->id,
161+
) = unserialize($serialized);
162+
}
143163
}
144164
145165
In order to use an instance of the ``AcmeUserBundle:User`` class in the Symfony
@@ -161,6 +181,15 @@ but it's also possible to do more checks depending on the complexity of your
161181
data model. On the other hand, the ``eraseCredentials()`` method remains empty
162182
for the purposes of this tutorial.
163183

184+
.. note::
185+
186+
The :phpclass:`Serializable` interface and its ``serialize`` and ``unserialize``
187+
methods have been added to allow the ``User`` class to be serialized
188+
to the session. This may or may not be needed depending on your setup,
189+
but it's probably a good idea. Only the ``id`` needs to be serialized,
190+
because the :method:`Symfony\\Bridge\\Doctrine\\Security\\User\\EntityUserProvider::refreshUser`
191+
method reloads the user on each request by using the ``id``.
192+
164193
Below is an export of my ``User`` table from MySQL. For details on how to
165194
create user records and encode their password, see :ref:`book-security-encoding-user-password`.
166195

@@ -361,7 +390,7 @@ The code below shows the implementation of the
361390
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $class));
362391
}
363392

364-
return $this->findOneById($user->getId());
393+
return $this->find($user->getId());
365394
}
366395

367396
public function supportsClass($class)

0 commit comments

Comments
 (0)