标题可能会产生误导,但我正在尝试做一些非常简单但却无法解决的问题。
假设我有一个问题控制器并显示操作,问题ID是我查找问题详细信息的主键 - 所以URL看起来像这样
http://www.example.com/question/show/question_id/101
这很好 - 所以当生成视图时 - URL显示如上所示。
现在在show动作中,我想要做的是,将问题标题(我从数据库中获取)附加到URL - 所以当生成视图时 - URL显示为
http://www.example.com/question/show/question_id/101/how-to-make-muffins
就像Stack溢出一样 - 如果你带任何问题页面 - 说
http://stackoverflow.com/questions/5451200/
然后按Enter键 问题标题作为
附加到网址http://stackoverflow.com/questions/5451200/make-seo-sensitive-url-avoid-id-zend-framework
非常感谢
答案 0 :(得分:2)
您必须向路由器添加自定义路由,除非您可以使用以下网址:
www.example.com/question/show/question_id/101/{paramName}/how-to-make-muffins
如果您想确保始终显示此参数,还需要检查参数是否在控制器中设置,并在缺少重定向时进行。
所以,在你的bootstrap文件中:
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
?>
在你的控制器中,你需要确保设置了title-parameter,或者如果没有,则需要重定向到自己的标题:
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 ...]
}
答案 1 :(得分:0)
这是使用301重定向完成的。
获取问题,过滤掉和/或替换URL非法字符,然后构造新URL。将其传递给Redirector
助手(在您的控制器中:$this->_redirect($newURL);
)