Search code examples
symfonydoctrine-ormannotationsmappingaccessor

Symfony2 / Doctrine2 : how to access an entity annotation mapping?


In my Symfony2/doctrine2 application, I have two entities, Media and Recipe.

They can be linked by a oneToMany or a ManyToMany association.

In the case of a oneToMany relationship, I am using the following code to retrieve the Recipe linked to an instance of Media :

$accessor = PropertyAccess::createPropertyAccessor();
$reflect = new ReflectionClass($media);
$shortName =  $reflect->getShortName();
$value = $accessor->getValue($element, $shortName);

However, if the relationship is a manyToMany, and also if I gave a custom name to the property, the previous code does not work.

How can I programatically retrieve the "recipes" of the mappedBy from the annotation mapping of the Media class ?

/**
 * @ORM\OrderBy({"sortablePosition" = "ASC"})
 * @Assert\Valid()
 * @ORM\ManyToMany(targetEntity="\AppBundle\Entity\Core\Media", mappedBy="recipes", cascade={"persist", "remove"})
 */
protected $medias;

Solution

  • What you need is a class that implements Doctrine\Common\Annotations\Reader interface. It is registered as a annotation_reader service. Having this class you can get annotations of various objects using methods like getClassAnnotation, getMethodAnnotations etc. In your case a getPropertyAnnotations seems to be a good choice:

    $reflClass = new \ReflectionClass($class); //$class is an instance of your entity
    $refProp = $reflClass->getProperty('medias');
    $annotations = $reader->getPropertyAnnotations($refProp);
    

    $annotations is a collection of annotations. In your case there will be 3 elements. Check doc for more info