https://www.bilibili.com/video/BV14E411t7T4?p=6
1 通过反射获取注释的简单使用案例
新建一个anntest文件夹
composer init
index.php
<?php require_once __DIR__.'/vendor/autoload.php'; /** * Class mytest * 我的注释 */ class mytest { } $c = new ReflectionClass(mytest::class); echo $c->getDocComment();
会打印出类的注释
2 使用第三方组件
2.1 部署
composer require doctrine/annotations 1.6
文档 https://blog.csdn.net/anhe0516/article/details/101188650
自动加载
\composer.json
"autoload": { "psr-4": { "App\\" : "app/" } }, "require": { "doctrine/annotations": "1.6" }
执行
composer dump-autoload
2.2 代码
D:\seckill\anntest\app\annotations\Value.php
namespace App\annotations; /** * @Annotation */ class Value { public $name; }
D:\seckill\anntest\app\test\MyRedis.php
class MyRedis { /** * @Value(name="url") */ public $conn_url; }
D:\seckill\anntest\index.php
<?php require_once __DIR__.'/vendor/autoload.php'; use \Doctrine\Common\Annotations\AnnotationReader; use \Doctrine\Common\Annotations\AnnotationRegistry; use \App\test\MyRedis; use \App\annotations\Value; //注册注释 AnnotationRegistry::registerLoader('class_exists'); //回调需返回true //AnnotationRegistry::registerAutoloadNamespace("App\annotations"); //AnnotationRegistry::registerFile(__DIR__ . '/app/annotations/Value.php'); //注册文件 //获取反射对象 MyRedis $rc = new ReflectionClass(MyRedis::class); //获取反射对象的变量 $p = $rc->getProperty("conn_url"); $reader = new AnnotationReader(); //获取变量的注释中@Value的name $anno = $reader->getPropertyAnnotation($p,Value::class); echo $anno->name;
运行后成功获取注释信息
3 利用注解动态读取配置文件
3.1 代码部署
3.1.1 配置文件 \.env
url = 127.0.0.1:8080
3.2.2 类的加载器 \app\core\ClassFactory.php
<?php /** * 类的加载器 */ namespace App\core; use Doctrine\Common\Annotations\AnnotationReader; class ClassFactory { public static function loadClass($className) { $refClass = new \ReflectionClass($className); //return $refClass->newInstance(); //获取所有的属性集合 $properties = $refClass->getProperties(); foreach ($properties as $property){ $read = new AnnotationReader(); $annos = $read->getPropertyAnnotations($property); foreach ($annos as $anno){ //var_dump($anno); $getValue = $anno->do(); //实例化 $obj = $refClass->newInstance(); //给属性赋值 $property->setValue($obj,$getValue); return $obj; } } return false; } }
3.2.3 业务类 \app\test\MyRedis.php
<?php namespace App\test; use App\annotations\Value; class MyRedis { /** * @Value(name="url") */ public $conn_url; }
3.2.4 注释类 \app\annotations\Value.php
<?php namespace App\annotations; /** * @Annotation */ class Value { public $name; public function do() { //return $this->name; $env = parse_ini_file('./.env'); if(isset($env[$this->name])){ return $env[$this->name]; } return false; } }
3.2 测试
成功动态加载的实例
4 注解类型
CLASS 类的注解
PROPERTY 属性
METHOD 方法
ALL 所有
ANNOTATION 注释的嵌套