CodeIgniter Forums

Full Version: Automatically loading config and language files of the same name as controller
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]Daniel H[/eluser]
Hi all

What is the most straight-forward way to load a config and language file of the same name as the controller you're currently accessing, if the files exist? I assume this would involve extending the controller class or perhaps a hook?

If anyone could give me some guidance on doing that I'd really appreciate it.

Many thanks,

Dan.

El Forum

[eluser]xwero[/eluser]
I would do it in the CodeIgniter/codeigniter.php file

above this line
Code:
call_user_func_array(array(&$CI, $method), array_slice($URI->rsegments, 2));
You can add
Code:
if(file_exists(APPPATH.'config/'.$class.EXT))
{
   $CI->load->config($class);
}

if(file_exists(APPPATH.'language/'.config_item('language').'/'.$class.EXT))
{
   $CI->load->lang($class);
}
The language class is more difficult because if the user is able to change the language you need to switch it before that file check otherwise the wrong language file is loaded.

El Forum

[eluser]Daniel H[/eluser]
Thanks xwero. Is there a way of doing it without changing the core file? I'd rather not do that.

The language files issue is okay: users can't change the language, I simply use it as a repository of semi-static text rather than using a db!

El Forum

[eluser]xwero[/eluser]
You can do it with hooks
Code:
// config/config.php
$config['enable_hooks'] = TRUE;
// config/hooks.php
$hook['post_controller_constructor'] = array(
                                'class'    => '',
                                'function' => 'autoload',
                                'filename' => 'post_controller_constructor.php',
                                'filepath' => 'hooks',
                                'params'   => array()
);
// hooks/post_controller_constructor.php
function autoload()
{
    $RTR =& load_class('Router');
    $class = $RTR->fetch_class();

    $CI =& get_instance();
    
    if(file_exists(APPPATH.'config/'.$class.EXT))
    {
       $CI->load->config($class);
    }

    if(file_exists(APPPATH.'language/'.config_item('language').'/'.$class.EXT))
    {
       $CI->load->lang($class);
    }
}
I don't know if it is working code but that should do it i think.

I rather work without hooks because i change the codeigniter.php file location in the index.php file so the original file is untouched.

El Forum

[eluser]Daniel H[/eluser]
Many thanks - I'll try it both ways and figure out what I feel most comfortable with.