Welcome Guest, Not a member yet? Register   Sign In
Automatically loading config and language files of the same name as controller
#1

[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.
#2

[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.
#3

[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!
#4

[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.
#5

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




Theme © iAndrew 2016 - Forum software by © MyBB