2.微服务-模拟实现注解形式的路由收集

入口文件index.php

<?php

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

Core\Application::init();

$server=new  Swoole\Http\Server('0.0.0.0',9501);
//方法注解

$server->on('request',function ($request,$response){
     var_dump(Core\Application::getBean('route'));
    //var_dump(\Core\Route::dispatch($request->server['path_info']));
});
$server->start();

init()方法

public static function init()
    {
        $loader = require dirname(__DIR__) . "/vendor/autoload.php";
        AnnotationRegistry::registerLoader([$loader, 'loadClass']);
        self::loadAnnotationRoute();//收集路由注解
        self::loadAnnotationBean();//收集容器注解
    }

//Registers an autoloading callable for annotations, much like spl_autoload_register()
public static function registerLoader(callable $callable) : void
    {
        // Reset our static cache now that we have a new loader to work with
        self::$failedToAutoload   = [];
        self::$loaders[]          = $callable;
    }

public static function loadAnnotationRoute()
    {
        //自动加载注解类(规则)到组件当中
        $reader = new Annotations\AnnotationReader();

        //手动实例化类 glob() 遍历文件
        $obj = new \App\Http\Controller\HomeController();
        $re = new \ReflectionClass($obj);

        //类注解
        $class_annos = $reader->getClassAnnotations($re);
        foreach ($class_annos as $class_anno) {
            $routePrefix = $class_anno->getPrefix();
            //通过反射得到所有的方法
            $refMethods = $re->getMethods();
            foreach ($refMethods as $method) {
//                var_dump($method->name);
                $methodAnnos = $reader->getMethodAnnotations($method);
                foreach ($methodAnnos as $methodAnno) {
                    $routePath = $methodAnno->getRoute();
                    //在某个解析类当中处理逻辑
                    (new RequestMappingParser())->parse($routePrefix, $routePath, $re->newInstance(), $method->name);
                }
            }
        }

 public static function loadAnnotationBean()
    {
        //自动加载注解类(规则)到组件当中
        $reader = new Annotations\AnnotationReader();
        //手动实例化类 glob() 遍历文件
        $obj = new Route();
        $re = new \ReflectionClass($obj);

//        var_dump($re);
        //类注解
        $class_annos = $reader->getClassAnnotations($re);
        foreach ($class_annos as $class_anno) {
            $beanName = $class_anno->getName();
            //parse方法作为作业
            self::$beans[$beanName]=$re->newInstance();
        }
    }

最后通过swoole开启一个http服务

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值