WEBcoast Logo

Serializing Symfony security user object

In one of my projects I used the VichUploaderBundle. The model with the file property is itself a property to my User class. The user object get's serialized and derserialized during request lifecycle. Because of this I ran into the quite familiar exception:

Serialization of 'Symfony\Component\HttpFoundation\File\File' is not allowed

Several times it was suggested to override the User class' `__serialize` and `__unserialize` methods. But I never found an anwser, which properties are necessary. After some try and error I came with the follwing implementation:

<?php

class User implements UserInterface
{
    ...


    /**
     * Return only the security relevant data
     *
     * @return array
     */
    public function __serialize(): array
    {
        return [
            'id' => $this->id,
            'email' => $this->email,
            'password' => $this->password,
        ];
    }

    /**
     * Restore security relevant data
     *
     * @param array $data
     */
    public function __unserialize(array $data): void
    {
        $this->id = $data['id'];
        $this->email = $data['email'];
        $this->password = $data['password'];
    }
}

I hope this will save someone some time in the future. This is from Symfony 5, but I expect this to work with both 4 and 6 too.