search
HomeBackend DevelopmentPHP TutorialPHP framework simple router
PHP framework simple routerNov 13, 2017 pm 01:41 PM
phpSimplerouter

路由的功能就是分发请求到不同的控制器,基于的原理就是正则匹配。接下来呢,我们实现一个简单的路由器,实现的能力是对于静态的路由(没占位符的),正确调用callback。

对于有占位符的路由,正确调用callback时传入占位符参数,譬如对于路由:/user/{id},当请求为/user/23时,传入参数$args结构为

[    'id' => '23'
]

大致思路

我们需要把每个路由的信息管理起来:http方法($method),路由字符串($route),回调($callback),因此需要一个addRoute方法,另外提供短方法get,post(就是把$method写好)

对于/user/{id}这样的有占位符的路由字符串,把占位符要提取出来,然后占位符部分变成正则字符串

实现

Route.php类

<?phpnamespace SalamanderRoute;class Route {    /** @var string */
    public $httpMethod;    /** @var string */
    public $regex;    /** @var array */
    public $variables;    /** @var mixed */
    public $handler;    /**
     * Constructs a route (value object).
     *
     * @param string $httpMethod
     * @param mixed  $handler
     * @param string $regex
     * @param array  $variables
     */
    public function __construct($httpMethod, $handler, $regex, $variables) {        $this->httpMethod = $httpMethod;        $this->handler = $handler;      
      $this->regex = $regex;        $this->variables = $variables;
    }    /**
     * Tests whether this route matches the given string.
     *
     * @param string $str
     *
     * @return bool
     */
    public function matches($str) {
        $regex = &#39;~^&#39; . $this->regex . &#39;$~&#39;;        return (bool) preg_match($regex, $str);
    }
}

Dispatcher.php

<?php/**
 * User: salamander
 * Date: 2017/11/12
 * Time: 13:43
 */namespace SalamanderRoute;class Dispatcher {    /** @var mixed[][] */
    protected $staticRoutes = [];    /** @var Route[][] */
    private $methodToRegexToRoutesMap = [];    const NOT_FOUND = 0;    const FOUND = 1;    const METHOD_NOT_ALLOWED = 2;    /**
     * 提取占位符
     * @param $route
     * @return array
     */
    private function parse($route) {
        $regex = &#39;~^(?:/[a-zA-Z0-9_]*|/\{([a-zA-Z0-9_]+?)\})+/?$~&#39;;        if(preg_match($regex, $route, $matches)) {            // 去掉full match
            array_shift($matches);            return [
                preg_replace(&#39;~{[a-zA-Z0-9_]+?}~&#39;, &#39;([a-zA-Z0-9_]+)&#39;, $route),
                $matches,
            ];
        }        throw new \LogicException(&#39;register route failed, pattern is illegal&#39;);
    }    /**
     * 注册路由
     * @param $httpMethod string | string[]
     * @param $route
     * @param $handler
     */
    public function addRoute($httpMethod, $route, $handler) {
        $routeData = $this->parse($route);        foreach ((array) $httpMethod as $method) {            if ($this->isStaticRoute($routeData)) {                $this->addStaticRoute($httpMethod, $routeData, $handler);
            } else {                $this->addVariableRoute($httpMethod, $routeData, $handler);
            }
        }
    }    private function isStaticRoute($routeData) {        return count($routeData[1]) === 0;
    }    private function addStaticRoute($httpMethod, $routeData, $handler) {
        $routeStr = $routeData[0];        if (isset($this->staticRoutes[$httpMethod][$routeStr])) {            throw new \LogicException(sprintf(                &#39;Cannot register two routes matching "%s" for method "%s"&#39;,
                $routeStr, $httpMethod
            ));
        }        if (isset($this->methodToRegexToRoutesMap[$httpMethod])) {            foreach ($this->methodToRegexToRoutesMap[$httpMethod] as $route) {                if ($route->matches($routeStr)) {                    throw new \LogicException(sprintf(                        &#39;Static route "%s" is shadowed by previously defined variable route "%s" for method "%s"&#39;,
                        $routeStr, $route->regex, $httpMethod
                    ));
                }
            }
        }        $this->staticRoutes[$httpMethod][$routeStr] = $handler;
    }    private function addVariableRoute($httpMethod, $routeData, $handler) {        list($regex, $variables) = $routeData;        if (isset($this->methodToRegexToRoutesMap[$httpMethod][$regex])) {            throw new \LogicException(sprintf(                &#39;Cannot register two routes matching "%s" for method "%s"&#39;,
                $regex, $httpMethod
            ));
        }        $this->methodToRegexToRoutesMap[$httpMethod][$regex] = new Route(
            $httpMethod, $handler, $regex, $variables
        );
    }    public function get($route, $handler) {        $this->addRoute(&#39;GET&#39;, $route, $handler);
    }    public function post($route, $handler) {        $this->addRoute(&#39;POST&#39;, $route, $handler);
    }    public function put($route, $handler) {        $this->addRoute(&#39;PUT&#39;, $route, $handler);
    }    public function delete($route, $handler) {        $this->addRoute(&#39;DELETE&#39;, $route, $handler);
    }    public function patch($route, $handler) {        $this->addRoute(&#39;PATCH&#39;, $route, $handler);
    }    public function head($route, $handler) {        $this->addRoute(&#39;HEAD&#39;, $route, $handler);
    }    /**
     * 分发
     * @param $httpMethod
     * @param $uri
     */
    public function dispatch($httpMethod, $uri) {
        $staticRoutes = array_keys($this->staticRoutes[$httpMethod]);        foreach ($staticRoutes as $staticRoute) {            if($staticRoute === $uri) {                return [self::FOUND, $this->staticRoutes[$httpMethod][$staticRoute], []];
            }
        }

        $routeLookup = [];
        $index = 1;
        $regexes = array_keys($this->methodToRegexToRoutesMap[$httpMethod]);        foreach ($regexes as $regex) {
            $routeLookup[$index] = [                $this->methodToRegexToRoutesMap[$httpMethod][$regex]->handler,                $this->methodToRegexToRoutesMap[$httpMethod][$regex]->variables,
            ];
            $index += count($this->methodToRegexToRoutesMap[$httpMethod][$regex]->variables);
        }
        $regexCombined = &#39;~^(?:&#39; . implode(&#39;|&#39;, $regexes) . &#39;)$~&#39;;        if(!preg_match($regexCombined, $uri, $matches)) {            return [self::NOT_FOUND];
        }        for ($i = 1; &#39;&#39; === $matches[$i]; ++$i);        list($handler, $varNames) = $routeLookup[$i];
        $vars = [];        foreach ($varNames as $varName) {
            $vars[$varName] = $matches[$i++];
        }        return [self::FOUND, $handler, $vars];
    }
}

配置

nginx.conf重写到index.php

location / {        try_files $uri $uri/ /index.php$is_args$args;        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 
       #        location ~ \.php$ {            fastcgi_pass   127.0.0.1:9000;            fastcgi_index  index.php;        
           fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;            include        fastcgi_params;        }    }
composer.json自动载入
{    "name": "salmander/route",    "require": {},    "autoload": {      "psr-4": 
{        "SalamanderRoute\\": "SalamanderRoute/"      } 
 }}

composer.json自动载入

{    "name": "salmander/route",    "require": {},    "autoload": {      "psr-4": 
{        "SalamanderRoute\\": "SalamanderRoute/"      }  }

最终使用

index.php

<?phpinclude_once &#39;vendor/autoload.php&#39;;use SalamanderRoute\Dispatcher;
$dispatcher = new Dispatcher();
$dispatcher->get(&#39;/&#39;, function () {    echo &#39;hello world&#39;;
});
$dispatcher->get(&#39;/user/{id}&#39;, function ($args) {    echo "user {$args[&#39;id&#39;]} visit";
});// Fetch method and URI from somewhere$httpMethod = $_SERVER[&#39;REQUEST_METHOD&#39;];
$uri = $_SERVER[&#39;REQUEST_URI&#39;];// 去掉查询字符串if (false !== $pos = strpos($uri, &#39;?&#39;)) {
    $uri = substr($uri, 0, $pos);
}
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);switch ($routeInfo[0]) {    case Dispatcher::NOT_FOUND:        echo &#39;404 not found&#39;;        break;    case Dispatcher::FOUND:
        $handler = $routeInfo[1];
        $vars = $routeInfo[2];
        $handler($vars);        break;
}

看了上面的这个案例大家应该对PHP实现简单路由器,有更清楚的认识吧,后期我们还会继续推出相关文章,大家有任何问题都可以踊跃发言,

相关推荐:

JS实现简单路由器功能的方法

怎样修改无线路由器密码 MySQL修改密码方法总结

php yaf框架中路由器问题

The above is the detailed content of PHP framework simple router. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.