views:

517

answers:

4

I'm trying to determine the best practice for calling multiple views from the same method in a controller.

Is it preferable in the controller to make one view call, then have that view call all the views it needs, or call all the views you need in sequence in the controller?

Example:

function index(){
   //set all data variables
   //then send them to the view
   $this->load->view($index_view, $data);
}

or

function index(){
  //set variables
  //then call each view
  $this->load->view($header_view, $header_data);
  $this->load->view($body_view, $body_data);
  $this->load->view($footer_view, $footer_data);

The Codeigniter guide shows both ways, but does not seem to advise to the best practice...is there one?

A: 

I don't think there is a definitive answer for that. Choose one and stick with it, it's important to be consistent.

Anyway, I'd prefer the second one.

Martín M.
A: 

I would say that the controller should only display one view. Then it's up to the view if it wants to show a header, footer, sidebar or whatever. The controller shouldn't have to care, its job is to get data from a model and hand it to a view. Not decide if the view should have a header and a footer.

Christian Davén
This is what I had been doing. It seems as if it is an OK practice to continue.
I agree with everything you said except the part where it is the job of the controller to get data from the model and hand it to the view. Views can do this as well. The Controller's job is to accept requests.
Thorpe Obazee
A: 

Agree with Christian Davén: its view / display logic not data or business / logic. essentially its the same as using php includes for snippets like navigation, footer etc. you're just embedding markup.

stef
+2  A: 

I didn't like the way of including the header/footer within the view, and I didn't like loading the footer and header each time in every single Controller function.

To fix this, I extended the Controller class with my own view display function.

<?php
// in application/libraries/MY_Controller.php
class MY_Controller extends Controller {
    function _displayPage($page, $data = array()) {
        $this->view->load('header', $data);
        $this->view->load($page, $data);
        $this->view->load('footer', $data);
    }
}
?>

// in application/controllers/home.php
<?php
class Home extends MY_Controller {
    function index() {
        $this->_displayPage('home/index', array('title' => 'Home'));
    }
}
?>

Not sure if this is CodeIgniter "best practice" but it makes sense to me.

jwpage