In my Symfony 5 project (PHP 8), I have set up a custom annotation called Uploadable.
Here is how I check that the @Uploadable annotation is present on an entity:
use Doctrine\Common\Annotations\AnnotationReader;
class UploadAnnotationReader
{
private AnnotationReader $reader;
public function __construct(private EntityManagerInterface $manager){
$this->reader = new AnnotationReader();
}
/**
* @throws \ReflectionException
*/
public function isUploadable($entity):bool
{
$reflection = new \ReflectionClass(get_class($entity));
return $this->reader->getClassAnnotation($reflection, Uploadable::class) !== null;
}
When I pass in parameter an entity (which does have the annotation that I created) obtained either directly from the database, or from the Symfony paramConverter, then the AnnotationReader is able to see this annotation.
On the other hand, if I get this entity back through a relation from another entity, oddly, it won't work anymore!
$entityA = $manager->getRepository(...)....;
$myService->isUploadable($entityA); // return true
$entityB = $manager->getRepository(...)....;
$myService->isUploadable($entityB->getEntityA()); // return false
$entityB = $manager->getRepository(...)....;
$entityA = $entityB->getEntityA();
$myService->isUploadable($entityB->getEntityA()); // return true
And I don't know why...
My Answer:
This issue might be related to how the entities are fetched and managed by Doctrine. When you access a related entity through a getter method like `$entityB->getEntityA()`, Doctrine might not fully initialize the related entity, including its annotations.
One way to ensure that the related entity is fully initialized is to use the `getReference()` method provided by Doctrine's EntityManager. This method will return a proxy object for the related entity without actually loading it from the database. This can help in ensuring that the annotations are properly read by the AnnotationReader.
Here's how you can modify your code to use `getReference()`:
php
$entityB = $manager->getRepository(...);
$entityA = $manager->getReference(EntityA::class, $entityB->getEntityA()->getId());
$myService->isUploadable($entityA); // should return true now
By using `getReference()`, you are telling Doctrine to provide a proxy object for `EntityA` without fully loading it from the database. This should help in ensuring that the annotations are properly read by the AnnotationReader.
Give this a try and see if it resolves the issue with reading annotations on related entities.
Rate this post
3 of 5 based on 9428 votesComments