2013-09-26 73 views
0

我yii PHP項目有UserController它有一個動作叫做actionView。我可以通過訪問用戶視圖頁面下面的URLYII框架用戶友好URL

mysite.com/user/view/id/1 

我想改變一個

mysite.com/username 

我怎麼能做到這一點。

我知道,我可以簡單地創建規則,以更加人性化得到URL,例如

mysite.com/user/username 

但隨着數據庫資源名稱作爲直接參數(mysite.com/username)URL方案是完全不同的故事。

+1

http://www.yiiframework.com/doc/guide/1.1/en/topics.url「2.用戶友好的網址」 –

+0

雖然這看起來像重複,但只有參數被使用的情況下url是有點不同的 – 2013-09-26 11:53:18

回答

1

URL規則:

array(
    '<username:\w+>'=>'user/view', 
) 

注意,在這種方案中,還必須在年底創建所有的控制器和地方上面的規則的規則,所以最好的前綴它與用戶:

array(
    'user/<username:\w+>'=>'user/view', 
) 

結果URL將example.com/user/username

在行動:

public function actionView($username) ... 

更新: 要使規則,反作用於任何輸入變量創建自定義URL規則類,這裏是一些例子,修改你的需求:

class PageUrlRule extends CBaseUrlRule 
{ 

     public function createUrl($manager, $route, $params, $ampersand) 
     { 
       // Ignore this rule for creating urls 
       return false; 
     } 

     public function parseUrl($manager, $request, $pathInfo, $rawPathInfo) 
     { 
       // Ignore/url or any controller name - which could conflict with username 
       if($pathInfo == '/') 
       { 
         return true; 
       } 
       // Search for username or any resource in db 
       // This is for mongo so it should be tuned to your db, 
       // just check if username exists 
       $criteria = new EMongoCriteria(); 
       $criteria->url->$lang = $url; 
       $criteria->select(['_id']); 
       $criteria->limit(1); 
       $model = PageItem::model(); 
       $cursor = $model->findAll($criteria); 
       // Create route, instead of $url id can be used 
       $route = sprintf('content/page/view/url/%s', urlencode($url)); 
       // If found return route or false if not found 
       return $cursor->count() ? $route : false; 
     } 

} 

然後把這個規則urlmanager配置的開始

'rules' => [ 
    [ 
     'class' => 'application.modules.content.components.PageUrlRule' 
    ], 
    // Other rules here 

重要:如果用戶的用戶名是一樣的控制器,它將匹配用戶名和控制器將無法訪問。您必須禁止註冊與控制器名稱相同的用戶。

+0

'example.com/user/username'不是我尋找的東西。我想刪除用戶部分。 我想'example.com/username'。 –

+1

最好創建客戶網址規則類,稍後發佈,我有類似的地方 – 2013-09-30 06:43:41