Jim Panse
Jim Panse

Reputation: 2270

Doctrine inheritance with only one table possible?

In my Doctrine model I want to have a BasePerson class which has all the database persisted fields.

 * @ORM\Entity()
class BasePerson 
{
   $street;
   $number;
   ...
}

I also want to have a Person class extending from the base person class which has additionally a entitylistener attached. The listener triggers an API call and filling my "Person" Entity with the location data.

 * @ORM\Entity()
 * @ORM\EntityListeners({"..."})
class Person extends BasePerson 
{
  $location;
}

For all base operations without needing API calls I want to use the BasePerson class, and for all API related operation I will use the Person class; but in every case I have at least the information coming from the database.

The problem now is, whenever I add the @ORM\Entity() annotation to both entities, Doctrine thinks this should be two tables. I don't want two tables. If I left the entity annotation on one of both entities, doctrine gives me an error, that this entity is unmanaged ...

How can I have it all in one table? I read about single table inheritance but for this, doctrine will manage this with an discriminator column ... but that's not the use case for my intend ...

Upvotes: 1

Views: 360

Answers (2)

T. AKROUT
T. AKROUT

Reputation: 1717

To have a clean architecture, you should use the same entity and two DTOs. One for the API and add it the attribute "location" and the other for other views of project.

Doctrine (version >= 2.4) can directly return a DTO from a query using "NEW" operator, an example:

<?php

$this
    ->get('doctrine.orm.entity_manager')
    ->createQueryBuilder()
    ->select('NEW Acme\DTO\CategoryListView(category.id, category.title)')
    ->from('AcmeDemoBundle:Category', 'category');

Upvotes: 1

Gregoire Ducharme
Gregoire Ducharme

Reputation: 1108

You can just have some method related to API in your Person class and use them only when needed. I don't see why this would be such an issue.

I don't think you should be using the BasePerson class directly. I assume Doctrine would not allow the behaviour you're trying to have.

Upvotes: 0

Related Questions