Home > Mobile >  Codeigniter global variable problems
Codeigniter global variable problems

Time:09-17

I need to use codeigniter global variable, I don't want to create a variable for each controller page, I want to do as we put it in the header in php, but I couldn't find a solution.

Example variable $template;

Controller 1:

    class Auth extends CI_Controller{
        public function index (){
         $this->load->view($template.'Auth')
       }
    }

Controller 2:

    class Loader extends CI_Controller{
        public function index (){
         $this->load->view($template.'Auth')
       }
    }

CodePudding user response:

//-create new file in:-//
/application/helpers/template_helper.php

<?php 
function admin_template() {
    return "admin/home";
}



//-From controller Auth-//

class Auth extends CI_Controller{
    function __construct(){
        parent::__construct();
        $this->load->helper('template');
    }
        public function index (){
         $data['info']="enter info here....";
         $this->load->view(admin_template().'Auth', $data)
       }
    }

can also auto load (template_helper.php): /application/config/autoload.php

CodePudding user response:

You can also create a base controller (eg BASE_Controller.php) under app/core; then define your global variable here(on the base controller). After that, just extend the base controller from the controllers. This approach could also come in handy for global functions like checking if user is logged in, fetching some global data like settings etc. See the example below:

app/core/BASE_Controller.php

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');



class BASE_Controller extends CI_Controller
{    
    public function __construct()
    {
        parent::__construct();        
        $this->data['info'] = "Your value goes in here";
        // if the info is declared from a function, do as:
        $this->data['logged_in'] = $this->checkStatus();
    }
    function checkStatus(){
     return false;
    }
    
   
}

then in app/controller/Controller.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Dashboard extends BASE_Controller {

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

    public function index()
    {
       $this->load->view($template.'Auth',$this->data);
    }

}

you can simply access your variables from the views as $array_index; for example, if you defined $this->data['info'], access is as:

$info;
//likewise, if you have $this->data['user_id'], access it as:
$user_id;

Fore controllers which extends the Base controller, just access it as:

//$this->data['variable'];
//example;
$user_id = $this->data['user_id'];
  • Related