codeeverything / junction
此包的最新版本(0.1)没有可用的许可证信息。
0.1
2016-03-24 12:55 UTC
Requires (Dev)
- phpunit/phpunit: ~4.0
This package is not auto-updated.
Last update: 2024-09-14 18:53:02 UTC
README
简单的PHP路由器
Junction是一个简单的PHP路由器。目前它是出于兴趣而创建的个人项目,但我计划将其用作我的微RESTful PHP框架Planck的默认路由器。
开源
欢迎评论和建议。这是一个开源项目,所以如果你想,请分支和提交PR! :)
测试
Junction附带了一组完整的测试。
您可以从shell中非常简单地使用PHPUnit运行它们
vendor/bin/phpunit
示例用法
简单路由
让我们定义一个简单的路由,只有一个路径段
// define the route $this->router->add('GET /hello', function () { // just return a string for the application to then work on return 'Hello, world'; }); // ... more routes ... // handle the request, matching routes if possible $response = $this->router->handleRequest();
add()
函数的第一个参数是一个以HTTP动词开始的字符串,后面跟请求的路径。
带有路径变量的简单路由
Junction允许您在路由中简单地定义变量,使用与您的数据库上的PDO查询类似的占位符语法
// define the route - with required variable "name" $this->router->add('GET /hello/:name', function ($name) { // just return a string for the application to then work on return 'Hello, ' . $name; }); // ... more routes ... // handle the request, matching routes if possible $response = $this->router->handleRequest();
"name"变量作为处理函数的第一个参数传递。
带有可选路径变量的简单路由
// define the route - with optional variable "name" $this->router->add('GET /hello/:name?', function ($name) { // just return a string for the application to then work on $name = isset($name) ? $name : 'world'; return 'Hello, ' . $name; }); // ... more routes ... // handle the request, matching routes if possible $response = $this->router->handleRequest();
如果给出了"name",则我们可以使用它,但如果省略了,则路由仍然会匹配,并且我们可以回退到字符串"world"。
变量验证
您可以通过提供一组验证回调函数来在路由中验证路径变量
$this->router->add('GET /hello/:name', [ 'name' => [ function ($value) { // only accept short names return strlen($value) < 5; }, ], ], function ($name) { return 'Hello, ' . $name; });
验证错误将引发一个Exception
,详细说明失败的变量和无效的值。