php 实现注解
PHP 实现注解的方法
PHP 本身不直接支持注解(Annotations),但可以通过反射(Reflection)和文档注释(DocBlock)结合第三方库实现类似功能。以下是几种常见实现方式:
使用 Doctrine Annotations 库
Doctrine Annotations 是 PHP 生态中广泛使用的注解解析库,适用于类、方法或属性的元数据标记。
安装库:
composer require doctrine/annotations
定义注解类:

use Doctrine\Common\Annotations\Annotation;
/
* @Annotation
* @Target("METHOD")
*/
class Route {
public $path;
public $methods = [];
}
使用注解:
use Doctrine\Common\Annotations\AnnotationReader;
class MyController {
/
* @Route(path="/user", methods={"GET"})
*/
public function getUser() {
// 方法逻辑
}
}
// 解析注解
$reader = new AnnotationReader();
$reflectionMethod = new ReflectionMethod('MyController', 'getUser');
$routeAnnotation = $reader->getMethodAnnotation($reflectionMethod, Route::class);
echo $routeAnnotation->path; // 输出 "/user"
利用 PHP 原生 Attributes(PHP 8+)
PHP 8 引入了原生属性(Attributes),可直接作为注解使用,无需依赖第三方库。
定义 Attribute 类:

#[Attribute(Attribute::TARGET_METHOD)]
class Route {
public function __construct(
public string $path,
public array $methods = []
) {}
}
使用 Attribute:
class MyController {
#[Route(path: '/user', methods: ['GET'])]
public function getUser() {
// 方法逻辑
}
}
// 解析 Attribute
$reflectionMethod = new ReflectionMethod('MyController', 'getUser');
$routeAttribute = $reflectionMethod->getAttributes(Route::class)[0]->newInstance();
echo $routeAttribute->path; // 输出 "/user"
自定义解析 DocBlock
若需兼容旧版本 PHP,可通过解析文档注释实现简单注解。
示例实现:
function parseAnnotations(string $docComment): array {
preg_match_all('/@(\w+)\s+(.*)/', $docComment, $matches);
return array_combine($matches[1], $matches[2]);
}
class MyService {
/
* @Cache ttl=3600
*/
public function heavyOperation() {}
}
$reflectionMethod = new ReflectionMethod('MyService', 'heavyOperation');
$annotations = parseAnnotations($reflectionMethod->getDocComment());
echo $annotations['Cache']; // 输出 "ttl=3600"
选择建议
- PHP 8+ 项目:优先使用原生 Attributes,性能更高且语法简洁。
- 旧版本 PHP:选择 Doctrine Annotations 或其他第三方库。
- 简单需求:自定义 DocBlock 解析足够轻量,但功能有限。






