PHP单文件路由类

文章介绍了PHP中的一个简单路由类`Router`的实现,该类用于处理HTTP请求的方法(如GET,PUT等)和URL路径,通过正则表达式匹配动态路由。配置文件展示了如何定义不同的路由规则,包括控制器实例化、回调函数以及静态方法的调用。在`index.php`中加载路由类和配置,然后进行路由解析。当请求不匹配任何路由时,会抛出404或405异常。
摘要由CSDN通过智能技术生成

PHP路由类

Router.php:

<?php

class Router
{
    private $routes = [];
    private $routeCount = 0;

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

    public function doRouting()
    {
        $is_match=0;
        // I used PATH_INFO instead of REQUEST_URI, because the
        // application may not be in the root direcory
        // and we dont want stuff like ?var=value
        $reqUrl = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);//$_SERVER['PATH_INFO'];

        if ($reqUrl == null) {
            $reqUrl = '';
        }
       

        $reqMet = $_SERVER['REQUEST_METHOD'];

        foreach ($this->routes as $route) {
            // convert urls like '/users/:uid/posts/:pid' to regular expression

             
            $patterns = array('/\[[a-zA-Z0-9\_\-\/]+\]/','/\[{[a-zA-Z0-9\_\-}]+\]/','/\[\/{[a-zA-Z0-9\_\-}]+\]/','/{[a-zA-Z0-9\_\-}]+/');
            $replace = array('([a-zA-Z0-9\-\_\/]*)','([a-zA-Z0-9\-\_]*)','([a-zA-Z0-9\-\_\/]*)','([a-zA-Z0-9\-\_]+)');


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

            $matches = array();
            // check if the current request matches the expression
            if (preg_match($pattern, $reqUrl, $matches)) {
                // remove the first match
                array_shift($matches);

                foreach ($matches as $key => $value) {
                    if (empty($value)) {
                        unset($matches[$key]);
                    }
                }
                // call the callback with the matched positions as params

                if ($route['method'] !=='*'  && $reqMet !=='HEAD'  && (
                    !empty($route['method']) &&
                    !in_array($reqMet, explode(',', $route['method'])))
                ) {
                    throw new Exception("405 Not Allowed");
                }
                

                return call_user_func_array($route['callback'], $matches);
            } else {
                $is_match++;
            }
        }

        if ($is_match == $this->routeCount) {
            throw new Exception("404 Not Found");
        }
    }
}


//autoload
// spl_autoload_register(function ($class_name) {
//     require_once __DIR__ . '/' .  str_replace('\\', '/', $class_name) . '.php';
// });

路由配置文件

config/route.php

<?php
return [


    [
        ['GET'],
        '/',
        [new App\Index, 'index'],
    ],
    [
        ['GET'],
        '/search',
        [new App\Index, 'search'],
    ],

    [
        ['GET'],
        '/tool-[id][/]',
        [new App\Index, 'tool'],
    ],

    [
        ['GET'],
        '/tool-[id]',
        [new App\Index, 'tool'],
    ],



    [
        ['GET'],
        '/category-[cid].html',
        [new App\Index, 'category'],

    ],


    [
        ['PUT,GET'],
        '/hello',
        function () {
            echo 'Hello AmazePHP!';
        },
    ],

    [
        ['GET'],
        '/hello2',
        'callbackFunction',
    ],

    [
        ['GET'],
        '/hello44.php',
        function () {
            include 'App/aaaaa.php';
        },
    ],

    [
        ['GET'],
        '/hello3/[id]',
        [new App\Foo, 'bar'],object, method
    ],

    [
        ['GET'],
        '/a/[uid]/b[/pid]',
        ['App\myclass', 'say_hello'],//static method
    ],

    [
        ['GET,POST'],
        '/users',
        function () {
            echo 'post AmazePHP';
        },
    ],

    [
        ['*'],
        '/users/[uid]/posts/[pid]',
        function ($uid, $pid = 99) {
            var_dump($uid, $pid);
        },
    ],

 
    ];

使用方法

index.php

include 'lib/Router.php';
include 'config/route.php';

$router = new Router();
foreach (config('route') as $key => $value) {
        $router->addRoute($value[0][0], $value[1], $value[2]);
}

$router->doRouting();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值