PHP 路由解析器结束 URL

标签 php router

我为自己的 php-mvc-framework 编写了一个小的 php url 解析器,我在下面的代码中几乎不需要帮助:

<?php
class Route{

private $routes = [];

public function __construct(){}

public function addRoute($method, $url, $callback){
    $this->routes[] = array('method' => $method, 
                          'url' => $url, 
                          'callback' => $callback);
}

public function doRouting(){
    $reqUrl = $_SERVER['REQUEST_URI'];
    $reqMet = $_SERVER['REQUEST_METHOD'];
    foreach($this->routes as  $route) {

        // convert urls like '/users/:uid/posts/:pid' to regular expression      
        $pattern = "@^" . preg_replace('/\\\:[a-zA-Z0-9\_\-]+/', '([a-zA-Z0-9\-\_]+)', preg_quote($route['url'])) . "$@D";
        $matches = array();

        if($reqMet == $route['method'] && preg_match($pattern, $reqUrl, $matches)) {

            // remove the first match
            array_shift($matches);
            // call the callback with the matched positions as params
            return call_user_func_array($route['callback'], $matches);
        }
    }
}

$route = new Route();

$route->addRoute('GET', '/', function(){
     echo 'root';
});

 $route->addRoute('GET', '/users/', function(){
     echo 'users';
 });
 $route->addRoute('GET', '/users/:uid/posts/:pid/', function($uid, $pid){
     echo $uid.'<br/>'.$pid;
 });

 $route->addRoute('GET', '/users/:uid/posts/:pid/edit', function($uid, $pid){
     echo 'users posts edit';
 });


 $route->doRouting();

我想在 URL 的末尾允许一个可选的 /。例如,在当前的路由定义中,当 REQUEST_URI/users/123/posts/456 我想要相同的结果(函数调用)当 REQUEST_URI/users/123/posts/456/

此外,/users/123/posts/456/edit 调用新函数。

最佳答案

如果需要,从您的 route 去除尾部斜线:

$route['url'] = rtrim($route['url'], '/');

然后相应地终止你的路线模式:

$pattern = preg_replace('/\\\:[a-zA-Z0-9\_\-]+/', '([a-zA-Z0-9\-\_]+)', preg_quote($route['url'], '@'));
$pattern = "@^$pattern/?$@D";

关于PHP 路由解析器结束 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20433870/

相关文章:

php - Symfony 2 - 在 Amazon S3 上上传图像的最佳实践

php - 我必须阅读并显示存储在数据库中的古吉拉特语字体

php - Mysql - 验证结果的一部分是否存在于另一个表中

go - httprouter.GET 不工作

angular - “在 Angular 区域外触发导航”解释

php - 为什么用php无法将日期写入mysql?

module - Zend框架2 : Router "resolves to invalid controller class or alias:"

javascript - 根据当前 URL React 渲染页脚

javascript - 在家里我得到那个错误 : The action 'SET_PARAMS' with the payload {"params": {"company" :"Marciello Resto 2"}} was not handled by any navigator

php - 数据库查询失败 : Incorrect integer value: '' for column 'id' at row 1