Passing common data to all loaded views – CI Tip

If you are just getting started with CI then you will quickly realize that in most cases you need to pass common sets of data to every view you load. From dynamic page titles, to current page variables to determine the current page for navigation, to common sets of data.

There is a ton of different ways you can go about handling this problem, personally I have always used the same method in most of my applications and its my personal preference to do it this way.

You will need to create a library in CI or use a helper (I prefer a library for this), I generally call mine ‘core’. Within this library create a function called ‘site_data’ or ‘common_data’. Within this function create a basic PHP array (key/value) with the same variable ($data for example) and then return that variable at the end of the function. (example below)

Now go to your controllers and anywhere you load a view change your function to look like the following function.

Example Controller:

public function index()
    // Set site_data from core library
    $data = $this->core->site_data();

    // Load view file
    $this->load->view('home', $data);


Example Library:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');	
class Core{
    public $CI;

    public function __construct()
        //Define CI based variables (so you can use CI functions)
        $this->CI =& get_instance();
    public function site_data()
        // Common variables that are used site wide in views
        $data['site_name'] =  $this->CI->config->item('site_name');
        $data['admin_email'] =  $this->CI->config->item('admin_email');
        $data['is_admin'] =  $this->account->admin_check(); 
        $data['cpage'] = ''; // Default for CPAGE Var
        $data['cpage_sub'] = ''; // Default for CPAGE_SUB Var
        return $data;

I hope this mini-tutorial will help you in this very common task with CI apps. Let me know in the comments below what you think and you are welcome to share how you best tackle this same common task.

Thanks for reading