2013-07-16 75 views
0

比方說,我希望有一個頁面,有一個漂亮的URL:CakePHP的路由:更改漂亮的URL站點範圍

配置/ routes.php文件

Router::connect('/profile', array('controller' => 'users', 'action' => 'profile')); 

如果我想發送旅客到頁面,我可以用這樣的網址:

$this->redirect('/profile'); 

$this->Html->link('Your Profile', '/profile'); 

但是,假設我改變了主意,我現在想要的網址是:

/account 

如何更改整個站點而不將每個/profile的實例更改爲/account

或者...

另一種方式來問我的問題是我怎麼能正確的代碼中使用蛋糕數組語法的所有URL(這是我喜歡做的,而不是硬編碼的任何東西):

$this->redirect(array('controller' => 'users', 'action' => 'profile')); 

$this->Html->link('Your Profile', array('controller' => 'users', 'action' => 'profile')); 

然後確保該控制器/動作組合稱爲任何時候,它會將用戶的網址:

/profile 

一nd將這條規則放在一個可以改變的地方。就像:

Router::connect(array('controller' => 'users', 'action' => 'profile'), '/profile'); 

// Later change to 

Router::connect(array('controller' => 'users', 'action' => 'profile'), '/account'); 

有沒有辦法做到這一點,也允許進一步的請求參數傳遞到URL添加?

回答

3

看一看路由文檔:http://book.cakephp.org/2.0/en/development/routing.html

在你app/routes.php附加:

Router::connect('/profile', array('controller' => 'users', 'action' => 'profile')); 

現在你可以創建你的鏈接是這樣的:

echo $this->Html->link('Link to profile', array('controller' => 'users', 'action' => 'profile')); 

或者,如果你想允許附加參數:

// When somebody comes along without parameters ... 
Router::connect('/profile', array('controller' => 'users', 'action' => 'profile')); 
// When somebody parses parameters 
Router::connect('/profile/*', array('controller' => 'users', 'action' => 'profile')); 

然後你就可以這樣做:通過

$userId = 12; 
echo $this->Html->link('Link to other profile', array('controller' => 'users', 'action' => 'profile', $userId)); 

然後$userId將可在控制器:

echo $this->request->params['pass'][0]; 
// output: 12 

這樣你就可以很容易地改變你的網址網站,而不必改變每一個視圖/重定向或以往任何時候。請記住,你不應該改變你的控制器名稱!因爲這會搞砸了很多。明智的選擇;-)

+1

這個職位有幫助的感謝 –

+0

@MukeshKumarBijarniya我很高興我能有所幫助:) – Jelmer