2011-03-18 28 views
6

我正在使用一個簡單的框架來處理基於查詢參數的請求。是否有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' 
    

任何幫助我s讚賞。

+0

您還可以看看Symfony2路由組件! – markus 2011-03-18 06:42:46

+0

看看[Moor](https://github.com/jeffturcotte/moor)和答案[here](http://stackoverflow.com/questions/11787176/manage-url-routes-in-own-php - 框架)和[這裏](http://stackoverflow.com/questions/20179984/custom-url-routing-with-php-and-regex)。 – user 2014-03-09 02:33:03

回答

8

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); 
+1

謝謝。這很簡單,我可以根據需要進行調整。我希望調度的路由解耦。 – Marco 2011-03-18 18:37:54

相關問題