一个简单的PHP单文件路由类示例

<?php
class Router {
    protected $routes = array();
    protected $basePath;
 
    public function __construct($basePath = null) {
        if ($basePath) {
            $this->basePath = rtrim($basePath, '/');
        } else {
            $this->basePath = '/';
        }
    }
 
    public function get($path, $callback) {
        $this->routes['GET'][$this->basePath . $path] = $callback;
    }
 
    public function post($path, $callback) {
        $this->routes['POST'][$this->basePath . $path] = $callback;
    }
 
    public function run() {
        $httpMethod = $_SERVER['REQUEST_METHOD'];
        $pathInfo = $_SERVER['PATH_INFO'];
 
        if (array_key_exists($pathInfo, $this->routes[$httpMethod])) {
            $callback = $this->routes[$httpMethod][$pathInfo];
            call_user_func($callback);
        } else {
            header('HTTP/1.0 404 Not Found');
            echo "404, Page not found";
        }
    }
}
 
// 使用示例
$router = new Router('/app');
$router->get('/hello', function() {
    echo "Hello, World!";
});
$router->run();

 

posted @ 2025-01-21 13:09  充实地生活着  阅读(20)  评论(0)    收藏  举报