aniruddh / phprouter
一个简单、轻量级且快速的PHP路由器,支持中间件和带斜杠或不带斜杠的模式。
v1.0.0
2022-09-30 17:50 UTC
Requires
- php: >=7.4.0
This package is auto-updated.
Last update: 2024-09-18 00:00:39 UTC
README
安装
使用composer安装
composer require aniruddh/phprouter
需要PHP 7.4或更高版本。
用法
以下是一个基本用法示例
require_once('path/to/vendor/autoload.php'); use Aniruddh\Router\Router; $router = new Router(); // default method is GET does not required to specify $router->add('/', function() { echo 'get Home page'; }); $router->add('/test', function() { echo 'get test1'; }); $router->add('/test', function() { echo 'post test'; }); //you can specify if you want $router->add('/test1', function() { echo 'get test1'; }, ['GET']); //Except GET you have to specify the method $router->add('/test1', function() { echo 'post test1'; }, ['POST']); //you can specify multiple method $router->add('/test2', function() { echo 'get and post test2'; }, ['GET', 'POST']); //set 404 if not default 404 page shown $router->set404(function(){ echo "<h1>404 not found! </h1> url: " . htmlentities($_SERVER['REQUEST_URI']); }); //run the router $router->run();
定义路由
//method and middleware must be an array $route->add($route, $callback, $method, $middleware);
//router use regex for route matching // Matches /users/42, but not /users/abc $router->add('/users/\d+', 'callback');
// Example with middleware $route->add('/users/\d+', 'callback', ['GET'], ['before'=> callabck, 'after'=> callback]);
//Example with class object and method $router->('/users', ['classname','method']);
//Example with trailing slash option enable require_once('path/to/vendor/autoload.php'); use Aniruddh\Router\Router; $router = new Router(true, 1); //default is false and 0 // 0 means without trailing slash // default method is GET does not required to specify $router->add('/', function() { echo 'get Home page'; }); $router->('/users', callback); //use can specify route like $router->('users', callback); both version will work
注意
即将推出...