WebNovice
WebNovice

Reputation: 2220

Codeigniter site wide views

I need to implement advertisements in the sidebar of my codeigniter site.

The advertisements are dynamic and retrieved from the database. My current setup is I have main template file, and I pass the name of the main view file to as a variable like below:

$data['main_content'] = 'some_view_file';
$this->load->view('template_file', $data);

I have thought of the following step:

  1. Make a function get_ads() in my MY_Controller and retrieve all ads and return it
  2. In each of my controller's method, I access the function created above and pass it to the template

$data['ads'] = $this->get_ads();
$data['main_content'] = 'some_view_file';
$this->load->view('template_file', $data);

But the problem with the above approach is, I need to set the $data['ads'] = $this->get_ads(); in all of my methods before loading the view.

What would be a better way to handle the above problem?

Upvotes: 1

Views: 220

Answers (2)

Madan Sapkota
Madan Sapkota

Reputation: 26111

Create a CodeIgniter Library called Ads.php

class Ads
{

    private $CI;

    public function __construct()
    {
        $this->CI = & get_instance();
    }

    public function my_ads()
    {
        // get the ads from database //
        return $this->CI->db->select('field1, field2, field3')->from('ads_table')->get()->result();
    }

}

Autoload the library (as you need ads in all views). Go to ./application/config/autoload.php

/*
  | -------------------------------------------------------------------
  |  Auto-load Libraries
  | -------------------------------------------------------------------
  | These are the classes located in the system/libraries folder
  | or in your application/libraries folder.
  |
  | Prototype:
  |
  | $autoload['libraries'] = array('database', 'session', 'xmlrpc');
 */

$autoload['libraries'] = array('ads');

Now you can retrieve the data all over CI system using

$ads = $this->ads->my_ads();

Hope this helps you. Thanks!!

Upvotes: 3

Yan Berk
Yan Berk

Reputation: 14438

In MY_Controller add a variable:

class MY_Controller extends CI_Controller {

      public $data;

      public function __construct() {
          $this->data['ads'] = $this->get_ads();      
          //etc.
      }
    //etc.
}

In each controller update the $data variable and call the view like this:

$this->data['main_content'] = 'some_view_file';
$this->load->view('template_file', $this->data);

Upvotes: 1

Related Questions