首页 后端开发 php教程 PHP框架之简单的路由器

PHP框架之简单的路由器

Nov 13, 2017 pm 01:41 PM
php 简单 路由器

路由的功能就是分发请求到不同的控制器,基于的原理就是正则匹配。接下来呢,我们实现一个简单的路由器,实现的能力是对于静态的路由(没占位符的),正确调用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框架中路由器问题

以上是PHP框架之简单的路由器的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

适用于 Ubuntu 和 Debian 的 PHP 8.4 安装和升级指南 适用于 Ubuntu 和 Debian 的 PHP 8.4 安装和升级指南 Dec 24, 2024 pm 04:42 PM

PHP 8.4 带来了多项新功能、安全性改进和性能改进,同时弃用和删除了大量功能。 本指南介绍了如何在 Ubuntu、Debian 或其衍生版本上安装 PHP 8.4 或升级到 PHP 8.4

CakePHP 使用数据库 CakePHP 使用数据库 Sep 10, 2024 pm 05:25 PM

在 CakePHP 中使用数据库非常容易。本章我们将了解CRUD(创建、读取、更新、删除)操作。

CakePHP 日期和时间 CakePHP 日期和时间 Sep 10, 2024 pm 05:27 PM

为了在 cakephp4 中处理日期和时间,我们将使用可用的 FrozenTime 类。

CakePHP 文件上传 CakePHP 文件上传 Sep 10, 2024 pm 05:27 PM

为了进行文件上传,我们将使用表单助手。这是文件上传的示例。

CakePHP 路由 CakePHP 路由 Sep 10, 2024 pm 05:25 PM

在本章中,我们将学习以下与路由相关的主题?

讨论 CakePHP 讨论 CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP 是 PHP 的开源框架。它的目的是使应用程序的开发、部署和维护变得更加容易。 CakePHP 基于类似 MVC 的架构,功能强大且易于掌握。模型、视图和控制器 gu

CakePHP 创建验证器 CakePHP 创建验证器 Sep 10, 2024 pm 05:26 PM

可以通过在控制器中添加以下两行来创建验证器。

CakePHP 日志记录 CakePHP 日志记录 Sep 10, 2024 pm 05:26 PM

登录 CakePHP 是一项非常简单的任务。您只需使用一项功能即可。您可以记录任何后台进程(如 cronjob)的错误、异常、用户活动、用户采取的操作。在 CakePHP 中记录数据很容易。提供了 log() 函数

See all articles