Search code examples
phpsymfonysymfony4

Why injecting EntityManagerInterface return me a Cannot serialize PhpFilesAdapter error


I have a problem that I've never encountered before even if I've done this on an other project. I tried to inject an EntityManagerInterface into my User entity (in order to fetch something in a configuration database). So I've used the @PostLoad technic.

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class User implements UserInterface
{
    /** @var EntityManagerInterface $em */
    private $em;
    /**
     * @ORM\PostLoad
     * @ORM\PostPersist
     */
    public function fetchEntityManager(LifecycleEventArgs $args)
    {
        $this->setEntityManager($args->getEntityManager());
    }

    public function setEntityManager($em) {
        $this->em=$em;
    }
}

I've already done this in an other project but not in the user entity and it worked just fine. But now I get this error:

Cannot serialize Symfony\Component\Cache\Adapter\PhpFilesAdapter

I think that creating a sort of utility class that could prevent me from injecting the entityManagerInterface in my entity will help me but I don't know what type of class should I use, a Service maybe ?


Solution

  • not entirely unrelated to your question: injecting an entity manager into an entity indicates a bad design and is not intended in symfony/doctrine's orm.

    what is causing your problem is, that the user is serialized by symfony's session management and when it tries to serialize a sufficiently complex object/service, it'll probably fail to do so. It is recommended to implement the Serializable interface to only serialize stuff that is actually needed (see same link). Which will solve this and other possible problems you might get. It also reduces the size of the session, which might get larger the bigger your application grows and attaches to the user object. Since the user object is loaded on every request anyway, serializing anything more than the mentioned properties (same link again) is simply wasteful.