php - 是否有可重复使用的 PHP 路由器/调度程序?

标签 php url-routing

我正在使用一个简单的框架来处理基于查询参数的请求。

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/

相关文章:

asp.net-mvc - 在 ASP.NET MVC 中创建 SiteMap

php - Yii2 中带有模块的自定义 URL 规则

playframework - Play Framework 是否支持像 rails 这样的嵌套路由?

php - 来自 mysql/php Json 编码数据和 Jquery 的 LazyLoad 内容

php - 检查 mysql_query 是否返回任何结果的最佳方法?

php - 如何在 API 平台中创建自定义端点并将其添加到文档中?

angular - 错误 : Cannot match any routes. URL 段: ''

javascript - 使用 crossroads.js 和 hasher.js 返回根页面

php - WordPress 二十四 : Make separation between posts thicker

php - 如何管理优惠券代码?