Yii - calling an action method from another action method

The header can be confusing, but here's an explanation with code.

Based on some conditions, I can call actionContact

even if the 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 the contact address.

I think solution 1 works great for me and I would prefer that. But since I'm new to yii I would like to know if this is the way to go?

+3


source to share


3 answers


Repeat code is rarely the right answer. Redirects come with 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.



+3


source


If this is not a problem you can 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');
}

      

+9


source


You can use the fourth option, which reorganizes the part that is common to indexing and contact action by the third method:

public function common() {
    // ...
}

public function actionIndex() {
    // ... call $this->common()
}

public function actionContact() {
    // ... call $this->common()
}

      

However, the best option depends on your specific case. For example, when you decide that you need to invoke another action, do you want to display its view too?

+3


source







All Articles