thomas-squall / php-magic-annotations
PHP的注解系统
0.9.7
2020-11-08 11:24 UTC
Requires
- php: >=5.6.0
- thomas-squall/string-utils: ^0.5.5
Requires (Dev)
- phpunit/phpunit: 5.*
README
PHP没有任何原生的注解(也就是.NET世界的属性)因此,如果你想实现自己的注解框架,首先考虑使用这个,这样可以节省一些时间。
安装
使用composer非常简单,只需运行以下命令
$ composer require thomas-squall/php-magic-annotations
使用方法
创建一个新的注解
首先,你需要创建一个新的类。在这个例子中,这个类将被称为 MyCustomAnnotation
class MyCustomAnnotation { }
然后,你需要从这个库中扩展 Annotation 类
use PHPAnnotations\Annotations\Annotation; class MyCustomAnnotation extends Annotation { }
为它添加一些逻辑
use PHPAnnotations\Annotations\Annotation; class MyCustomAnnotation extends Annotation { private $name; private $surname; public function __constructor($name, $surname) { $this->name = $name; $this->surname = $surname; } public function GetFullName() { return "$this->name $this->surname"; } }
现在我们的漂亮的注解已经准备好了!
使用注解
创建一个用于测试注解的类
class MyTestClass { }
然后通过文档添加注解
/** * @MyCustom(name = "Thomas", surname = "Cocchiara") **/ class MyTestClass { }
现在我们可以测试它了!
use use PHPAnnotations\Reflection\Reflector; $myObject = new MyTestClass(); $reflector = new Reflector($myObject); echo $reflector->getClass()->getAnnotation("MyCustom")->GetFullName();
希望你们觉得这个库很有用。
请分享它并给我反馈 :)
托马斯