您將有一個自定義的路由添加到您的路由器,除非你可以像一個URL生活:
www.example.com/question/show/question_id/101/{paramName}/how-to-make-muffins
還,如果您要確保該參數總是顯示出來,需要檢查參數是否在控制器中設置,如果缺失則發出重定向。
所以,在引導文件:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
public function _initRoutes()
{
// Ensure that the FrontController has been bootstrapped:
$this->bootstrap('FrontController');
$fc = $this->getResource('FrontController');
/* @var $router Zend_Controller_Router_Rewrite */
$router = $fc->getRouter();
$router->addRoutes(array (
'question' => new Zend_Controller_Router_Route (
/* :controller and :action are special parameters, and corresponds to
* the controller and action that will be executed.
* We also say that we should have two additional parameters:
* :question_id and :title. Finally, we say that anything else in
* the url should be mapped by the standard {name}/{value}
*/
':controller/:action/:question_id/:title/*',
// This argument provides the default values for the route. We want
// to allow empty titles, so we set the default value to an empty
// string
array (
'controller' => 'question',
'action' => 'show',
'title' => ''
),
// This arguments contains the contraints for the route parameters.
// In this case, we say that question_id must consist of 1 or more
// digits and nothing else.
array (
'question_id' => '\d+'
)
)
));
}
}
現在,你有這條路線,你可以用它在你的看法,像這樣:
<?php echo $this->url(
array(
'question_id' => $this->question['id'],
'title' => $this->question['title']
),
'question'
);
// Will output something like: /question/show/123/my-question-title
?>
在你的控制器,你需要確保標題參數被設置,或者如果不是,則使用標題集重定向到自己:
public function showAction()
{
$question = $this->getQuestion($this->_getParam('question_id'));
if(!$this->_getParam('title', false)) {
$this->_helper->Redirector
->setCode(301) // Tell the client that this resource is permanently
// residing under the full URL
->gotoRouteAndExit(
array(
'question_id' => $question['id'],
'title' => $question['title']
)
);
}
[... Rest of your code ...]
}
感謝Patrik的詳細信息。我不確定您對控制器所做的更改。雖然在我所有的觀點中,我將標題設置爲URL的一部分 - 但是用戶可能只需將URL輸入爲www.example.com/question/show/123 - 但沒有標題 - 因此標題不是必需的。但是我想要的是,即使用戶輸入了上面的網址 - 頁面呈現時 - 網址應該有標題。如果你輸入http://stackoverflow.com/questions/5451200/就像在stackoverflow - 標題會自動附加。那麼這就是你在控制器裏做什麼。 – Gublooo 2012-03-07 10:28:12
是的,標題是可選的提供,但如果沒有提供,控制器將301永久重定向到相同的URL,但附加了標題。你必須做一個重定向,你不能改變url的外觀。 – PatrikAkerstrand 2012-03-07 10:30:37
哦謝謝我剛剛看到您的回覆 - 所以當我將該代碼添加到控制器時 - 我將重定向到主頁。 – Gublooo 2012-03-07 10:33:59