1

I am new with Codeigniter(CI) and playing with codes but I need some guidance to make this things complete.

Let's say I have written this code to with some conditions:

if(isset($_COOKIE["lang"]) && !empty($_COOKIE["lang"])){
    if($_COOKIE["lang"] == "en"){
        $this->lang->load('en', 'english');
    }else{
        $this->lang->load('du', 'dutch');
    }
}else{
    $cookie = array(
                'name'   => 'lang',
                'value'  => 'en',
                'expire' => 604800
            );
    $this->input->set_cookie($cookie);
}

Now I want to load this code on every page to check which language file to load.

I have tried with this way:

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

    if(isset($_COOKIE["lang"]) && !empty($_COOKIE["lang"])){
        if($_COOKIE["lang"] == "en"){
            $this->lang->load('en', 'english');
        }else{
            $this->lang->load('du', 'dutch');
        }
    }else{
        $cookie = array(
                    'name'   => 'lang',
                    'value'  => 'en',
                    'expire' => 604800
                );
        $this->input->set_cookie($cookie);
    }

}

but If I have lots of controller file so I can't go to change each an every file. Is there any simple way to manage at one place in codeigniter.

tereško
  • 58,060
  • 25
  • 98
  • 150
Mr.Happy
  • 2,639
  • 9
  • 40
  • 73

1 Answers1

1

You can achieve this by using CI Hooks

Make sure you enable hooks in application/config/config.php :

$config['enable_hooks'] = TRUE;

$hook['pre_controller'] = function()
{
    $CI =& get_instance();
    if(isset($_COOKIE["lang"]) && !empty($_COOKIE["lang"])){
        if($_COOKIE["lang"] == "en"){
            $CI->lang->load('en', 'english');
        }else{
            $CI->lang->load('du', 'dutch');
        }
    }else{
        $cookie = array(
            'name'   => 'lang',
            'value'  => 'en',
            'expire' => 604800
        );
        $CI->input->set_cookie($cookie);
    }
};
Touqeer Shafi
  • 5,084
  • 3
  • 28
  • 45