views:

677

answers:

2

Hi friends,

I use codeigniter. I have footer_view.php, header_view.php and other view php files for pages like aboutus, contactus, etc... for example for about us page, I create model for db actions, than I create a controller to get db variables and send variable to about us view as:

$this->load->view('aboutus/',$data);

everthing is fine until this point. but when I need to get data from db at footer, how will I use mvc way? if I create a footer_model, i cannot make view('footer/') because it is actually a part if page, not a page itself :/

I hope I could explain my issue... I appreciate helps!! Thanks!

A: 

I wrote a blog post about this http://joshhighland.com/blog/2008/11/09/how-i-do-layouts-and-views-in-codeigniter/

basically, you want to load all the data that all your views are going to need in the controller. I use an array of data elements, then pass that to the layout view. My blog post explains more about this, and shows more detail. Here is a sample of my controller.

$this->load->model('search');

$lastest_albums = $this->search->last_n_albumsAdded(10);
$popular_songs = $this->search->popular_n_songs(10);
$featuredAlbums = $this->search->getFeaturedAlbums();

$body_data['featured'] = $featuredAlbums;
$body_data['newest'] = $lastest_albums;
$body_data['popular'] = $popular_songs;

$layout_data['content_body'] = $this->load->view(’home/homePage’, $body_data, true);

$this->load->view('layouts/main', $layout_data);
JoshHighland
+1  A: 

You can use $this->load->vars($data);

This will make all data available to all views, footer_view.php, header_view.php and any other views.

$data['your_info'] = $this->user_model->get_info();
$data['your_latest_info'] = $this->user_model->get_latest_info();
$data['your_settings_info'] = $this->user_model->get_settings_info();

$this->load->vars($data);

$this->load->view('your_view');

You view can and will access the data like so:

Your "primary" view

<?php
// your_view.php
// this can access data
$this->load->view('header_view');
<?php foreach ($your_info as $r):?>
<?php echo $r->first_name;?>
<?php echo $r->last_name;?>
<?php endforeach;?>
$this->load->view('footer_view');
?>

Your header_view

<?php
// header_view.php
<?php echo $your_latest_info->site_name;?>
?>

Your footer_view

<?php
// footer_view.php
<?php foreach ($your_setting_info as $setting):?>
<?php echo $setting->pages;?>
<?php endforeach;?>
?>

No need for any template library...

Thorpe Obazee