【问题标题】:How to autoload custom annotation classes without using AnnotationRegistry?如何在不使用 AnnotationRegistry 的情况下自动加载自定义注释类?
【发布时间】:2023-03-27 00:10:01
【问题描述】:

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

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
{

}

注解/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.

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

【问题讨论】:

    标签: php doctrine-orm annotations composer-php autoload


    【解决方案1】:

    我发布了一个类似的问题并自己回答了,因为它的答案显然比我想象的要模糊得多,最终花了一整天的时间来追查,尽管很容易解决:

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

    详情请见https://stackoverflow.com/a/59966965/4538469

    【讨论】:

      【解决方案2】:

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

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

      use Doctrine\Common\Annotations\AnnotationRegistry;
      
      if (class_exists(AnnotationRegistry::class)) {
          AnnotationRegistry::registerLoader('class_exists');
      }
      

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

      【讨论】:

      • v2.0以后才可以不用Registry的自动加载对吗?
      猜你喜欢
      • 1970-01-01
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      • 2013-10-29
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多