Search code examples
phpcodeigniterhmvccodeigniter-3codeigniter-hmvc

Codeigniter 3.x - Preload $data to ALL views alongside dynamic data


Question:

Out of curiosity, I'm wondering if Codeigniter provides a way to have specific data always loaded into a view.

For example: I have a config file that contains site information that would be beneficial to have access to inside of a view for all pages, rather than having to call to load that data every time a load a view, could I always have it included?


<?php
    //Standard way
    function index() {

        $this->load->config('site_settings', true);
        $data['config'] = $this->config->item('site_settings');
        $data['fizz'] = 'buzz';

        $this->load->view('index', $data);
    }

    //Way I'd like to see
    function index() {
        $data['foo'] = 'bar';
        $this->load->view('index', $data); //$data already includes $data['config']
    }
?>

Option 1:

Some kind of MY_Loader Extension - We already have a MY_Controller, so it wouldn't be too far fetched to do a MY_Loader Class and have MY_Controller call that instead of CI_Loader. However, I'm not sure this is possible.

Option 2:

I know this is possible if you edit system files, but I would really prefer not doing that. As that makes changes hard to track when updating CI.

Option 3:

???


Thoughts?

Edit For Clarification: This is specifically for loading data into views, extending CI_Controller and setting member variables there are ONLY accessible from models and controllers NOT views.


Solution

  • Thank you all for the answers! I figured it out!

    You can actually extend over Codeigniter's CI_Loader Class which is pretty cool!

    /application/core/MY_Loader.php

    class MY_Loader extends CI_Loader
    {
        protected $data;
    
        public function __construct()
        {
            parent::__construct();
        }
    
        public function preload($data = array())
        {
            $this->data = $data;
        }
    
        public function view($view, $vars = array(), $return = FALSE)
        {
            array_merge($vars, $this->data);
            return parent::view($view, $vars, $return);
        }
    }
    

    Usage:

    /application/core/MY_Controller.php

    class MY_Controller extends CI_Controller
    {
        public function __construct()
        {
            //Load CI In
            parent::__construct();
            $this->load->preload(array('foo' => 'bar'));
        }
    }
    

    /application/controllers/Controller.php

    class Controller extends MY_Controller
    {
    
        public function __construct()
        {
            parent::__construct(); // !!IMPORTANT
        }
    
        public function index() 
        {
            $this->load->view('index', array('fizz' => 'buzz'));
        }
    }
    

    /application/views/index.php

    <?php var_dump($foo, $fizz); ?>
    

    Output:

    "bar"
    "buzz"