首页 > 解决方案 > Doctrine AnnotationReader 不适用于关系实体

问题描述

在我的 Symfony 5 项目(PHP 8)中,我设置了一个名为 Uploadable 的自定义注释。

以下是我检查实体上是否存在@Uploadable注释的方法:

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;
    }

当我传入参数时,直接从数据库或从 Symfony paramConverter 获得的实体(确实具有我创建的注释),然后 AnnotationReader 能够看到此注释。

另一方面,如果我通过另一个实体的关系取回这个实体,奇怪的是,它不再起作用了!

$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

而且我不知道为什么...

标签: phpsymfonyannotationsdoctrinereader

解决方案


固定的。Juste 使用Doctrine\Common\Util\ClassUtils::getClass而不是 php 本机函数 ' get_class '


推荐阅读