Swoole实战之手撸HttpServer框架 9 使用方法注解 注册路由
作者:互联网
https://www.bilibili.com/video/BV14E411t7T4?p=13
1 添加方法注释
1.1 \app\controllers\UserController.php
use Core\annotations\RequestMapping;
/** * @RequestMapping(value="/user/test") * */ public function test() { return "路由注释"; }
2 添加RequestMapping注释
\core\annotations\RequestMapping.php
<?php /** * Created by PhpStorm. * User: SUN * Date: 2022/1/29 * Time: 21:03 */ namespace Core\annotations; use Doctrine\Common\Annotations\Annotation\Target; /** * @Annotation * @Target({"METHOD"}) */ class RequestMapping { public $value='';//路径 如/api/test public $method = [];// GET。POST }
3 路由收集器
\core\init\RouterCollector.php
<?php namespace Core\init; use Core\annotations\Bean; /** * 路由收集器 * @Bean() */ class RouterCollector { public $routes = []; public function addRouter($method,$uri,$handler) { $this->routes[] = [ 'method'=>$method, 'uri'=>$uri, 'handler'=>$handler]; } }View Code
4 载入init里的路由收集器 与添加处理方法的注释
\core\BeanFactory.php
//扫描(重点) $scans = [ //必须扫描的文件夹 ROOT_PATH."/core/init"=>"Core\\", //用户配置的扫描路径 self::_getEnv("scan_dir",ROOT_PATH."/app")=> self::_getEnv("scan_root_namespace","APP\\") ]; //$scanDir = self::_getEnv("scan_dir",ROOT_PATH."/app"); //$scanRootNamespace = self::_getEnv("scan_root_namespace","APP\\"); foreach ($scans as $scanDir=> $scanRootNamespace){ self::ScanBeans($scanDir,$scanRootNamespace); }
private static function handlerMethodAnno(&$instance,\ReflectionClass $refClass,AnnotationReader $reader) { //读取反射对象的属性 $methods = $refClass->getMethods();//取出所有的方法 foreach ($methods as $method){ //$prop必须是反射对象属性 $methodAnnos = $reader->getMethodAnnotations($method); foreach ($methodAnnos as $methodAnno){ //返回对象实例 obj 所属类的名字。如果 obj 不是一个对象则返回 FALSE $handler = self::$handlers[get_class($methodAnno)]; $handler($method,$instance,$methodAnno); } } }
5 方法注释处理器
\core\annotationhandlers\RequestMapping.php
<?php namespace Core\annotationhandlers; use Core\annotations\RequestMapping; use Core\BeanFactory; return[ //$methodAnnoSelf 注解本身 RequestMapping::class=>function(\ReflectionMethod $method,$instance,$methodAnnoSelf){ $path = $methodAnnoSelf->value;//uri; $requestMethod = count($methodAnnoSelf->method)>0 ? $methodAnnoSelf->method:['GET']; $RouterCollector = BeanFactory::getBean("RouterCollector"); $RouterCollector-> addRouter($requestMethod,$path,function() use($method,$instance){ $method->invoke($instance);//执行反射方法 }); return $instance; } ];
6 测试
\test.php
$routerCollector= \Core\BeanFactory::getBean("RouterCollector"); var_dump($routerCollector->routes);
标签:core,HttpServer,Swoole,self,instance,php,method,路由,RouterCollector 来源: https://www.cnblogs.com/polax/p/15929943.html