如何在不使用 AnnotationRegistry 的情况下自动加载自定义注释 类?

How to autoload custom annotation classes without using AnnotationRegistry?

我正在使用 Doctrine Annotations 库(不是整个 Doctrine,只有注释)并且想制作自定义注释 class。

composer.json:

{
  "require": {
    "doctrine/annotations": "^1.6"
  },
  "autoload": {
    "psr-4": {
      "annotations\": "annotations",
      "entities\": "entities"
    }
  }
}

index.php:

<?php

require 'vendor/autoload.php';

use Doctrine\Common\Annotations\AnnotationReader;

$annotationReader = new AnnotationReader();
$reflectionClass = new ReflectionClass(entities\MyClass::class);
$classAnnotations = $annotationReader->getClassAnnotations($reflectionClass);
var_dump($classAnnotations);

entities/MyClass.php

<?php

namespace entities;

use annotations\TestAnnotation;

/**
 * @TestAnnotation("123")
 */
class MyClass
{

}

annotations/TestAnnotation.php

<?php

namespace annotations;

/**
 * @Annotation
 * @Target("CLASS")
 */
final class TestAnnotation
{
    /**
     * @var string
     */
    public $value;
}

它给我以下错误:

[Semantical Error] The annotation "@annotations\TestAnnotation" in class entities\MyClass does not exist, or could not be auto-loaded.

我在互联网上找到的唯一解决方案是使用 AnnotationRegistry::registerLoader 或类似的东西,但它已被弃用,所以我想用另一种方式解决问题。

解决注册加载器的一种方法是在应用程序 bootstrap 期间的某处显式 require_once 所有带有自定义注释的文件(这种方法曾在 MongoDB ODM 中使用,但已被删除).

在下一个主要版本中 annotations 将依赖于自动加载,因此设置不需要任何代码。要获得面向未来的代码,您可以使用:

use Doctrine\Common\Annotations\AnnotationRegistry;

if (class_exists(AnnotationRegistry::class)) {
    AnnotationRegistry::registerLoader('class_exists');
}

您可以显式传递 Composer 的自动加载器,但 class_exists 可以正常工作,因为 Composer 的自动加载器已经在使用中。

我发布了一个类似的问题并自己回答了这个问题,因为显然这个问题的答案比我想象的要晦涩得多,最终花了一整天的时间来追踪,虽然很容易修复:

composer require “yogarine/doctrine-annotation-autoload”
composer dump-autoload

详情见。