php+swoole实现注解路由原理

①    通过composer引入doctrine组件:

"require": {

    "doctrine/annotations":"^1.6"

  }

②    注册路由和路由分发两大步,用的是swoole框架可以通过静态变量存储在内存中

(1)   注册路由:

在doctrine包里有个自动加载注解类(规则)到组件当中的方法 (这样就不会产生文件不存在或者找不到而报错)

    $loader = require dirname(__DIR__) . "/vendor/autoload.php";

AnnotationRegistry::registerLoader([$loader,'loadClass']);

通过glob()函数去注册所有路由

    $reader = new AnnotationReader(); // 注解的读取类
    // 类注解,通过反射获取对应类的对象,可以从中取出类注解的所有前缀、属性、方法注释对象
  $re = new ReflectionClass($obj);
  $class_annos = $reader->getClassAnnotations($re);
    // 通过反射得到所有的方法
    $refMethods = $re->getMethods();
    // 读取注解方法信息
    $methodAnnos = $reader->getMethodAnnotations($method);
    $routePath = $methodAnno->getRoute();
  // 在某个解析类当中处理逻辑
  (new RequestMappingParser())->parse($routePrefix,$routePath,$re->newInstance(),$method->name);

完成注册路由

(2)路由分发

      

       通过request对象获取路由,遍历所有注册路由去匹对,调用控制器以此完成路由分发。

注:注解类型

原文地址:https://www.cnblogs.com/zhyphp/p/14836630.html