11

I am attempting to create an abstracted getId method on my base Entity class in Symfony2 using Doctrine2 for a database where primary keys are named inconsistently across tables.

When inspecting entity objects I see there is a private '_identifier' property that contains the information I am trying to retrieve but I am not sure how to properly access it.

I'm assuming there is some simple Doctrine magic similar to:

public function getId()
{
    return $this->getIdentifier();
}

But I haven't managed to find it on the intertubes anywhere.

wallyk
  • 56,922
  • 16
  • 83
  • 148
Lord_Baine
  • 182
  • 1
  • 1
  • 10
  • Do you have any way to normalize your identifiers, or is that out of your control? – Problematic May 25 '11 at 20:27
  • Unfortunately I don't. Most tables are named TablenameID, but some are CmpTablenameID. They are all annotated via @orm:Id in their respective entity though. – Lord_Baine May 25 '11 at 20:35

1 Answers1

27

You can access this information via EntityManager#getClassMetadata(). An example would look like this:

// $em instanceof EntityManager
$meta = $em->getClassMetadata(get_class($entity));
$identifier = $meta->getSingleIdentifierFieldName();

If your entity has a composite primary key, you'll need to use $meta->getIdentifierFieldNames() instead. Of course, using this method, you'll need access to an instance of EntityManager, so this code is usually placed in a custom repository rather than in the entity itself.

Hope that helps.

Problematic
  • 17,567
  • 10
  • 73
  • 85
  • You can see the thread in the doctrine-user Google group where I unintentionally found this answer because of a different problem [here](https://groups.google.com/forum/#!topic/doctrine-user/7I4VYhwV_0Y). – Problematic May 26 '11 at 20:59
  • 1
    Is there any way to access this information from the entity instead of the repository? – Lord_Baine May 27 '11 at 18:02
  • 1
    I suppose you could pass into the constructor. Or, if you have some control of your entities, implement an IdentifiableInterface or something and return it manually. There's no magic to do this, as entities are simply plain old PHP objects. – Problematic Jun 04 '11 at 06:33
  • Actually, this can be handled with reflection in java. So i guess, can be solved by reflection in php as well – webyildirim Sep 03 '14 at 09:26