Welcome Guest, Not a member yet? Register   Sign In
Passing chunk of code to every controller
#1

(This post was last modified: 09-12-2015, 08:14 AM by Keky. Edit Reason: clarification )

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);
    }

CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#3

(This post was last modified: 09-13-2015, 02:00 AM by Keky. Edit Reason: typo )

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




Theme © iAndrew 2016 - Forum software by © MyBB