简体   繁体   中英

Codeigniter - How to load some code on every page?

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.

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);
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM