我正在使用一个简单的框架来处理基于查询参数的请求。
http://example.com/index.php?event=listPage
http://example.com/index.php?event=itemView&id=1234
我想把干净的 url 放在前面,这样你就可以通过这种方式访问它:
http://example.com/list
http://example.com/items/1234
我知道路由和调度是如何工作的,我可以自己写。但我宁愿利用已经解决这个问题的所有代码。有谁知道提供此功能的通用库或类,但会让我从路由匹配中返回我想要的任何内容?像这样。
$Router = new Router();
$Router->addRoute('/items/:id', 'itemView', array( 'eventName' => 'itemView' ));
$Router->resolve( '/items/1234' );
// returns array( 'routeName' => 'itemView',
// 'eventName' => 'itemView,
// 'params' => array( 'id' => '1234' ) )
基本上,我可以根据从路径中解析出的值自行进行调度。如果不是太麻烦(并且只要许可证允许),我不介意将其从框架中移除。但通常我发现框架中的路由/调度有点过于集成,无法像这样重新调整用途。我的搜索似乎表明,如果人们不使用框架,他们就会自己编写。
一个好的解决方案应该支持以下内容:
- 用冒号或正则表达式指定路由
- 从路由中解析出参数并以某种方式返回它们
像这样支持快速反向查找:
$Router->get( 'itemView', array( 'id' => '1234' ) ); // returns 'items/1234'
感谢任何帮助。
最佳答案
GluePHP可能非常接近你想要的。它提供一项简单的服务:将 URL 映射到类。
require_once('glue.php');
$urls = array(
'/' => 'index',
'/(?P<number>\d+)' => 'index'
);
class index {
function GET($matches) {
if (array_key_exists('number', $matches)) {
echo "The magic number is: " . $matches['number'];
} else {
echo "You did not enter a number.";
}
}
}
glue::stick($urls);
关于php - 是否有可重复使用的 PHP 路由器/调度程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5348837/