[英]Is there a reusable router / dispatcher for PHP?
我正在使用一個簡單的框架來處理基於查詢參數的請求。
http://example.com/index.php?event=listPage
http://example.com/index.php?event=itemView&id=1234
我想在此前面放置干凈的網址,以便您可以通過以下方式訪問它:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.