Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 / Doctrine 2: Two Entities for the same table, use one in favour of the other

In my Symfony2 application I extracted most of my Entities into a separate library which I install using composer.

This library does not have a dependency on Symfony2 (but does depend on Doctrine because I use annotations), because I would like to use it in other non-Symfony2 projects as well.

The library contains a ClientUser Entity, which maps to a client_users table. In my Symfony2 application, I would like to use the same ClientUser Entity for authentication. This requires me to implement Symfony\Component\Security\Core\User\UserInterface.

The problem is that I would like to have both a 'Symfony2-agnostic' and a 'Symfony-aware' implementation of a ClientUser Entity (which both should map to the same table). I tried to extend both classes from a ClientUserAbstract Entity, but it didn't work.

<?php
namespace My\Library\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\MappedSuperClass
 */
class ClientUserAbstract {

    // all my fields here
}

My "Symfony2-agnostic" Entity:

<?php
namespace My\Library\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class ClientUser extends ClientUserAbstract {

    // nothing here, it's empty
}

My "Symfony2-aware" Entity:

<?php
namespace Vendor\Bundle\MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity
 */
class ClientUser extends ClientUserAbstract implements UserInterface {

    // all methods that Symfony requires because of the UserInterface here:
    public function getRoles();
    public function getPassword();
    public function getSalt();
    public function getUsername();
    public function eraseCredentials();
}

My Symfony 2 app now detects two Entities which point to the same table and fails with an Exception. I either need to tell my Symfony2 app to "ignore" my My\Library\Entity\ClientUser, or I need a way to extend it. Any ideas?

like image 678
Yeroon Avatar asked May 30 '14 13:05

Yeroon


1 Answers

Just in case anyone else has this issue, here is my comment converted to an answer:

For a given entity manager, it's strictly one entity per table. You need to create a second entity manager and use it for authentication.

Plus of course, I like getting reps.

like image 148
Cerad Avatar answered Nov 14 '22 10:11

Cerad