php handles routing class sharing for restful requests

  • 2021-01-19 22:04:00
  • OfStack


<?php
    class Router {
        //  The routing table 
        private $routers = array(
            array("name"=>"userlist", "pattern"=>"get /user", "action"=>"User#get"),
            array("name"=>"userinfo", "pattern"=>"get /user/:s", "action"=>"User#getById"),
            array("name"=>"useradd", "pattern"=>"post /user", "action"=>"User#add"),
            array("name"=>"userupdate", "pattern"=>"update /user", "action"=>"User#update"),
            array("name"=>"userdel", "pattern"=>"delete /user/:id", "action"=>"User#delete")
        );
        //  The entrance 
        public function dispatch() {
            $url = $_SERVER["REQUEST_URI"];
            $method = $_SERVER["REQUEST_METHOD"];
            foreach ($this->routers as $router) {
                $pattern = $router["pattern"];
                $pats = explode(" ", $pattern);
                if (strcasecmp($pats[0], $method) == 0) {
                    //  Matches the current route 
                    $params = $this->checkUrl($method, strtolower($url), strtolower($pats[1]));
                    if ($params != null) {
                        array_shift($params);
                        $action = $router["action"];
                        //  To find the first 1 The route that matches is executed and returned 
                        return $this->invoke($action, $params);
                    }
                }
            }
            echo "404 error";
            // error 404
        }
        private function invoke($action, $params) {
            $acts = explode("#", $action);
            $className = $acts[0]."Action";
            $methodName = $acts[1];
            $actionDir = dirname(__FILE__).DIRECTORY_SEPARATOR."action";
            //  load action file 
            $classFile = $actionDir.DIRECTORY_SEPARATOR.$className.".php";
            if (! file_exists($classFile)) {
                // 404 error
                echo "404 error, no action found";
                return;
            } else {
                require "$classFile";
                //  Use reflection execution methods 
                $rc = new ReflectionClass($className);
                if (! $rc->hasMethod($methodName)) {
                    // 404 error
                    echo "404 error, no method found";
                    return;
                } else {
                    $instance = $rc->newInstance();
                    $method = $rc->getMethod($methodName);
                    $method->invokeArgs($instance, $params);
                }
            }
        }
        //  Check the regular match and extract the parameters 
        private function checkUrl($method, $str, $pattern) {
            //echo "check $str with $pattern <br>";
            $ma = array();
            $pattern = ltrim(rtrim($pattern, "/"));
            $pattern = "/".str_replace("/", "\/", $pattern)."\/?$/";
            $pattern = str_replace(":s", "([^\/]+)", $pattern);
            //echo "pattern $pattern<br>";
            //$str = "/\".$str."$/";
            if (preg_match($pattern, $str, $ma) > 0) {
                return $ma;
            }
            return null;
        }
    }
?>


Related articles: