标题可能令人困惑,但这里有代码解释。
基于某些条件,即使用户拨打了actionIndex
,我也可以打电话actionContact
。
解决方案:1
public function actionIndex()
{
$a = 5;
if($a == 5){
$this->actionContact();
}
else{
$this->render('index');
}
}
public function actionContact()
{
// Some codes
$this->render('contact');
}
解决方案:2
public function actionIndex()
{
$a = 5;
if($a == 5){
// Repeat code from actionContact method
$this->render('contact');
}
else{
$this->render('index');
}
}
解决方案:3 我可以重定向到联系人网址。
我认为,解决方案 1 对我来说效果很好,我更喜欢这样。但是由于我是刚接触yii,我想知道,如果这是要走的路?
如果不是问题,您可以使用 forward
http://www.yiiframework.com/doc/api/1.1/CController#forward-detail
public function actionIndex()
{
$a = 5;
if($a == 5){
// Forward user to action "contact"
$this->forward('contact');
}
else{
$this->render('index');
}
}
public function actionContact()
{
// Some codes
$this->render('contact');
}
"
重复代码"很少是正确答案。重定向涉及额外的开销,在我看来,它们应该主要用于响应 POST 操作,而不是像这样。在这种情况下,我会选择解决方案 1。
您可以使用第四个选项,即将索引和联系操作通用的部分重构为第三种方法:
public function common() {
// ...
}
public function actionIndex() {
// ... call $this->common()
}
public function actionContact() {
// ... call $this->common()
}
不过,最佳选择取决于您的具体情况。例如,当您决定必须调用其他操作时,是否也要呈现其视图?