• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Passing chunk of code to every controller

#1
Hi,

I want to display some data on every page (like latest news, latest comments etc).

So I created the Latest_model.php and autoload it. For example this is the simple function for getting the latest news.

Code:
  public function get_latest_news()
{

               $this->db->order_by("id", "desc");
               $query = $this->db->get('news', 10);
               return $query->result_array();
}

I put this in my template view (sidebar.php)

Code:
         <?php foreach ($latest_news as $latest_news_item): ?>
         <?php echo $latest_news_item['title']; ?><br>
         <?php endforeach; ?>

Now, let's look at some controller, for example History.php (which main function is to show history stuff in content template).

Code:
public function index()
{
     
       $data['history'] = $this->history_model->get_history();

I want this only in history.php. So, now finally for my main problem. If I want to display latest news, comments etc... in the sidebar on every page, I have to put these lines in EVERY controller

Code:
      $data['latest_news'] = $this->latest_model->get_latest_news();
      $data['latest_comments'] = $this->latest_model->get_latest_comments();
      ...


How can I pass the code for displaying latest things without the need to writing it to every controller?
Reply

#2
You can extend CI_Controller with your own MY_Controller. See http://www.codeigniter.com/userguide3/ge...core-class

Then set your data in the constructor :


PHP Code:
class MY_Controller extends CI_Controller
{
    public $data;

    public function __construct()
    {
        parent::__construct();
        $this->data['latest_news'] = $this->latest_model->get_latest_news();
        $this->data['latest_comments'] = $this->latest_model->get_latest_comments();
    }
}

class 
Some_controller extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $this->load->view('your_view'$this->data);
    }

Test your translation files with Translation Tester
Reply

#3
Thank you for your response.
Unfortunately, I can't get it to work. I get this error:

Message: Undefined variable: latest_news

Sorry, my bad, it is working perfectly!
I was just executing it incorrectly.

Thanks again!
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.