<?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();
标签:function,示例,basePath,callback,routes,path,PHP,路由 From: https://www.cnblogs.com/cblx/p/18683435