2

i would need to use the domain and put it in a session, to retrieve some data out of the database. I can do this in my default controller, no problem with that. The problem is when people link directly to a specific controller like: www.mywebsite/mycontroller/myfunction.

When they enter the website via this link, i don't set the session from the domain and i'll get some errors.

So my question is: Does someone have a solution to check/set this session in every function of every domain?

Thanks in advance!

1
  • 1
    Could you not put some logic within the construct? Commented Mar 31, 2014 at 14:51

1 Answer 1

4

You can use a hook : http://ellislab.com/codeigniter/user-guide/general/hooks.html

Or you can code your small script into the construct of your controllers.

function __construct()
{
    parent::__construct();
    //Put your code here, you can also load your models and stuff
    //$this->load->model("user_model","user");
    //Code code code
}

And here is an example of a hook for i18n (language module) -- Create a file under applications/hooks/my_hook.php

function setUserLang()
{
//Getting the language of the user
//If nothing was found, stick with English
$ci =& get_instance();
if(!$ci->session->userdata('lang')){
    $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
    switch ($lang){
        case "fr":
            $ci->session->set_userdata('lang','french');
            break;

        case "en":
            $ci->session->set_userdata('lang','english');
            break;

        default:
            $ci->session->set_userdata('lang','english');
            break;
    }
}
}

And go to applications/config/hooks.php and add something like :

$hook['post_controller_constructor'][] = array(
            'class'     => '',
            'function'  => 'setUserLang',
            'filename'  => 'my_hook.php',
            'filepath'  => 'hooks'
            );
Sign up to request clarification or add additional context in comments.

2 Comments

Hooks is something new for me, but it seems to be the perfect solution.. Many thanks!
Ya know, hooks, I haven't explored much in my years of working with CI. I actually have a base controller that runs a custom build preDispatch function which does whatever I need. However, I think I should look into putting some of that logic into hooks too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.