2012-10-29 54 views
1

我想知道是否有一個簡單和最佳實踐的方式來使CakePHP(routes.php文件)中的路線將用戶標識映射到虛榮url?將CakePHP路由到虛榮URL

我有(可怕的方式做到這一點),在我的路線頁面下面的測試代碼:

$users = array 
(
    1 => 'firstname-lastname', 
    2 => 'firstname2-lastname2' 
); 

//profiles 
foreach($users as $k => $v) 
{ 
    // LESSONS (Profiles) 
    Router::connect('/:user', array('controller' => 'teachers', 'action' => 'contentProfile', $k), 
     array('user' => '(?i:'.$v.')')); 
} 

上面的代碼路徑我的老師控制器conProfile作爲動作從:

mydomain.com/teachers/contentProfile/1 
to 
mydomain.com/firstname-lastname 

我可以從路由頁面連接到數據庫嗎?在性能方面這不是一個好主意嗎?讓我知道做這件事的最好方法是什麼。

回答

4

您可以創建一個自定義路由類,它將在數據庫中查找傳遞的URL並將其轉換爲正確的用戶ID。設置較長的緩存時間應該可以減輕打到數據庫的任何性能影響。

The book documentation是有點薄,不過,但基本結構是這樣的:

class TeachersRoute extends CakeRoute { 

    /** 
    * Modify incoming parameters so that controller receives the correct data 
    */ 
    function parse($url) { 
    $params = parent::parse($url); 

    // Add/modify parameter information 

    // The teacher id should be sent as the first value in the $params['pass'] array 

    return $params; 
    // Or return false if lookup failed 
    } 

    /** 
    * Modify parameters so calls like HtmlHelper::url() output the correct value 
    */ 
    function match($url) { 
    // modify parameters 

    // add $url['slug'] if only id provided 

    return parent::match($url); 
    } 

,然後在路線:

Router::connect(
    '/:slug', 
    array(
    'controller' => 'teachers', 
    'action' => 'contentProfile' 
), 
    array(
    'slug' => '[a-zA-Z0-9_-]+' 
    'routeClass' => 'TeachersRoute', 
) 
); 
+0

由於這是我想要的。是的,這本書也有點薄。 – cdub

+2

馬克故事還有一篇關於自定義路線類的較早文章:http://mark-story.com/posts/view/using-custom-route-classes-in-cakephp – gapple

+0

是的,當我看到你的時候我正在閱讀那篇文章也回答。 Thx再次。 – cdub