我正在尝试定义和使用自定义注释,但我无法弄清问题所在。基础是教义/注释,这是我自己的课程:
<?php
namespace MyCompany\Annotations\Annotation;
use Doctrine\Common\Annotations\Annotation;
/**
* @Annotation
* @Target("PROPERTY")
*/
final class Type
{
/**
* @Required
*
* @var string
*/
public $name;
}
<?php
namespace MyCompany\Annotations;
use MyCompany\Annotations\Annotation as MYC;
class Person
{
/**
* @MYC\Type(name = "string")
*/
private $firstName;
/**
* @MYC\Type(name = "string")
*/
private $lastName;
public function __construct($firstName, $lastName)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
}
public function getFirstName()
{
return $this->firstName;
}
public function getLastName()
{
return $this->lastName;
}
}
现在,我想阅读所有属性的注释:
<?php
require __DIR__ . '/../vendor/autoload.php';
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\CachedReader;
use Doctrine\Common\Cache\ArrayCache;
use MyCompany\Annotations\Person;
$refClass = new ReflectionClass(Person::class);
$props = $refClass->getProperties();
foreach ($props as $prop) {
$reader = new AnnotationReader();
$annotationReader = new CachedReader(
$reader, new ArrayCache()
);
$annotations = $annotationReader->getPropertyAnnotations(
$prop
);
print_r($annotations);
}
如果我运行测试脚本,它将失败并显示以下错误:
Uncaught exception 'Doctrine\Common\Annotations\AnnotationException' with message '[Semantical Error] The annotation "@MyCompany\Annotations\Annotation\Type" in property MyCompany\Annotations\Person::$firstName does not exist, or could not be auto-loaded.'
让我感到困惑的是,错误消息中的类名以'@'字符开头。
答案 0 :(得分:0)
您错过了注册注解的电话(您的注解和您正在使用的所有内部注解)。最简单的方法是将Composer自动加载器直接传递给Doctrine的registerLoader
方法:
$loader = require_once 'vendor/autoload.php';
Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, "loadClass"]);
位于测试脚本的顶部。
这假定您正在通过Composer完成所有自动加载,但如果没有,这里in the manual
中提供了一些方法来注册单个文件或名称空间。