Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a dynamic variable value global in CodeIgniter?

How to make a global variable that always changing?

I want to create something like protected $global_data; in controller Global_data.php that can be called by a lot of controller, and return variable $global_data value to whenever controller that has $this->load->library('../controllers/Global_data').

But when I tried to call it, it gives me this error Unable to locate the specified class: Session.php, so I think CodeIgniter 3.1.8 not allowed me to do this.

So how to achieve what I'm looking for? do I need to put it on model instead, library file or is there another way to do it?

Thank you.

Here is Global_data.php content

protected $global_data;

public function __construct()
{
    parent::__construct();

    $this->global_data = array(
        'can_be_anything'    => 'can_be_anything',
        'can_be_anything'    => 'can_be_anything',
        'can_be_anything'    => 'can_be_anything',
        'can_be_anything'    => 'can_be_anything',
    );
}

Can_be_anything_controller.php content

class Can_be_anything_controller extends CI_Controller {
    public function __construct()
    {
        parent::__construct();

        $this->load->library('../controllers/Global_data');
    }

    public function index()
    {
        $data = $this->global_data;
        $data['page_title']     = 'Dashboard';
        $data['page_directory'] = 'pages/dashboard';
        $this->load->view('template', $data);
    }
}
like image 809
Khrisna Gunanasurya Avatar asked Mar 29 '26 17:03

Khrisna Gunanasurya


1 Answers

You may create a library for that in libraries directory

Global_data.php file

class Global_data{
  public $global_data;

  protected $CI;

  public function __construct() {
    $this->CI = & get_instance();
  }

  public function common_data()
  {

    $this->global_data= array(
        'can_be_anything'    => 'can_be_anything',
        'can_be_anything'    => 'can_be_anything',
        'can_be_anything'    => 'can_be_anything',
        'can_be_anything'    => 'can_be_anything',
    );
    return $this->global_data;
  }

 public function any_method(){
   $query = $this->CI->db->get('table_name');
 }
}

Now you can load it in any controller like

$this->load->library('Global_data')

Then use data

$data = $this->Global_data->common_data();

Also you may use HMVC model to use any method in any controller

https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc

like image 142
Rejoanul Alam Avatar answered Apr 03 '26 16:04

Rejoanul Alam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!