Reputation: 28995
Title may be confusing, but here's explanation with code.
Based on some conditions,
I may call actionContact
even if user has called actionIndex
.
Solution:1
public function actionIndex()
{
$a = 5;
if($a == 5){
$this->actionContact();
}
else{
$this->render('index');
}
}
public function actionContact()
{
// Some codes
$this->render('contact');
}
Solution:2
public function actionIndex()
{
$a = 5;
if($a == 5){
// Repeat code from actionContact method
$this->render('contact');
}
else{
$this->render('index');
}
}
Solution:3 I can redirect to contact url.
I think, solution 1 works fine for me and I would prefer that. But since I am new to yii, I would like to know, if its the way to go ?
Upvotes: 3
Views: 11098
Reputation: 2134
If its not problem, you could use 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');
}
Upvotes: 8
Reputation: 111219
You could use a fourth option, which is refactoring the part that is common to index and contact actions into a third method:
public function common() {
// ...
}
public function actionIndex() {
// ... call $this->common()
}
public function actionContact() {
// ... call $this->common()
}
The best option depends on your particular case, though. For example, when you decide you have to call a different action, do you want to render its view, too?
Upvotes: 3
Reputation:
"Repeat code" is very rarely the correct answer. Redirects involve additional overhead, and in my opinion they should mostly be used in response to POST actions, not like this. In this case I would go with solution 1.
Upvotes: 3