Search code examples
phpcodeignitersidebar

What is the ideal way to populate a sidebar with Dynamic Data?


I require a help for a sidebar. I checked some of the solutions here but could not figure out how to resolve it. Hence this post.

The sidebar lists all the available categories of something. This data is pulled from category table in mysql. Scenario is such that I need to dislay this sidebar in all pages. I have a view for sidebar. What I am doing right now is that I created a custom core controller, MY_Controller by extending the CI_Controller. I have a function called get_all_categories in My_Controller. Then in the index function of all other page controllers, I have this;

$categories = $this->get_all_categories();
$this->load->view('template/header');
$this->load->view('template/sidebar', $categories);
$this->load->view('home/index');
$this->load->view('template/footer');

I am not an expert in CI. Just learning. So just wanted to know if this is the right way to do it. Please advise...


Solution

  • Nothing is wrong with your approach however it is more common to move the get_all_categories function into a model, autoloading it, and then you could just do $this->somemodel->get_all_categories() you could even make a convenience function so you don't have to repeat the header and footer like so:

    Model:

    function template($main_view, $data = array()) {
        $categories = $this->get_all_categories();
        $this->load->view('template/header');
        $this->load->view('template/sidebar', $categories);
        $this->load->view($main_view, $data);
        $this->load->view('template/footer');
    }