fatcode / annotations
1.2.0
2019-03-27 19:04 UTC
Requires
- php: >=7.2.0
- ext-mbstring: *
Requires (Dev)
- mockery/mockery: >=1.2
- phpunit/phpunit: >=8.0
- squizlabs/php_codesniffer: >=3.0
- vimeo/psalm: >=3.2
This package is auto-updated.
Last update: 2024-08-28 22:52:33 UTC
README
简介
Annotations 通过扩展文档块注释,尝试为 PHP 提供元数据编程。语法与最新的 注解 RFC 兼容。
安装
composer install fatcode/annotations
与 RFC 的差异
以下注解因各种原因不支持:
@Compiled
- 因为没有编译过程@SupressWarning
- 在用户空间中没有简单的方法来实现它@Repeatable
- 所有注解默认可重复@Inherited
- 与@SupressWarning
相同,在用户空间中没有简单的方法跟踪 PHP 的继承树
内置注解
@Annotation()
- 使类可作为注解使用@Required()
- 确保在使用注解时传递属性@NoValidate()
- 关闭属性验证@Enum(mixed ...$value)
- 定义注解属性的合法值@Target(string ...$target)
- 声明注解的有效目标
定义注解
<?php declare(strict_types=1); use FatCode\Annotation\Target; /** * @Annotation * @Target(Target::TARGET_CLASS) */ class MyAnnotation { /** * @Required * @var string */ public $name; }
上面的示例定义了一个仅对 PHP 类有效的注解(@Target(Target::TARGET_CLASS)
)。注解将接受一个必需的属性 name
,它必须是 string
类型(@Required
)。
使用注解
<?php declare(strict_types=1); /** * @MyAnnotation(name="Hello World") */ class AnnotatedClass { }
上面的示例使用了新声明的 MyAnnotation
注解。
检索注解
检索类注解
<?php declare(strict_types=1); use FatCode\Annotation\AnnotationReader; $reader = new AnnotationReader(); $annotations = $reader->readClassAnnotations(AnnotatedClass::class); var_dump($annotations); /* will output: array(1) { [0] => class MyAnnotation#19 (1) { public $name => string(11) "Hello World" } } */
示例代码可以在 这里 找到。