bellevue / router
支持路径变量的小型路由库。
dev-master
2016-02-26 10:11 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: 4.8.*
This package is auto-updated.
Last update: 2024-08-29 03:36:46 UTC
README
支持路径变量的小型路由库。
示例
路由到常规函数
路由
$routes = [ '/home' => [ 'function' => 'main' ] ];
PHP
<?php use BellevueRouter\src\Router; require_once 'routes.php'; $router = new Router($routes); $router->route('/home'); function main() { echo 'Hello!'; }
路由到静态类方法
路由
$routes = [ '/home' => [ 'class' => 'StaticRoutes', 'method' => 'main' ] ];
PHP
<?php use BellevueRouter\src\Router; require_once 'routes.php'; $router = new Router($routes); $router->route('/home'); class StaticRoutes { public static function main() { echo 'Static class method.' } }
路由到对象实例方法。
路由
$routes = [ '/home' => [ 'object' => 'Routes', 'method' => 'sayHi' ] ];
PHP
<?php use BellevueRouter\src\Router; require_once 'routes.php'; $router = new Router($routes); $router->route('/home'); class Routes { public static function sayHi() { echo 'Object instance method.' } }
路径变量到函数参数
要传递给函数的参数在参数数组中给出。它们将按照这里定义的顺序传递给函数,所以如果你的函数定义看起来像myFunc($var1, $var2)
并且你的参数数组是['val1, 'val2']
,myFunc将接收这些值作为$var1和$var2变量。
你还可以通过路径的命名部分将路径值注入到你的函数中。也就是说,如果你有一个路径如/post/{id}
,路由器将在你的参数数组中查找具有相同名称的字符串:{id}
,并将其替换为用户在路径中输入的值。所以如果用户访问路径/post/12
,并且你有你的参数数组如['{id}']
,字符串“12”将被作为第一个函数参数传递。
以下示例显示了完整参数的使用。
路由
$clientIp = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unknown'; $routes = [ '/hi/{name}' => [ 'function' => 'hi', 'arguments' => ['{name}', $clientIp] ] ];
PHP
<?php use BellevueRouter\src\Router; require_once 'routes.php'; $router = new Router($routes); $router->route('/hi/Yoshi'); function hi($name, $ip) // variables can have any name here. { printf('Hello, %s! Your IP address is %s', $name, $ip); }
注意
路由器不执行路径变量净化。如果指定了变量,则从下一个正斜杠或字符串末尾之前的每个字符都将被捕获并传递给你的函数。
默认路由
还有一个可选的默认路由,可以在没有给定路径或没有匹配路径时调用。
路由
$clientIp = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unknown'; $routes = [ 'default' => [ 'function' => 'home', ] ];
PHP
<?php use BellevueRouter\src\Router; require_once 'routes.php'; $router = new Router($routes); $router->route('unmatched'); function home() { echo 'Welcome home!'; }