How to add autoload-function to CodeIgniter?

无人久伴 提交于 2019-12-01 18:04:11

You can add your auto loader above to app/config/config.php. I've used a similar autoload function before in this location and it's worked quite neatly.

function __autoload($class)
{
    if (strpos($class, 'CI_') !== 0)
    {
        @include_once(APPPATH . 'core/' . $class . EXT);
    }
} 

Courtesy of Phil Sturgeon. This way may be more portable. core would probably be records for you; but check your paths are correct regardless. This method also prevents any interference with loading CI_ libs (accidentally)

the User guide about Auto-loading Resources is pretty cleat about it.

To autoload resources, open the application/config/autoload.php file and add the item you want loaded to the autoload array. You'll find instructions in that file corresponding to each type of item.

I would suggest using hooks in order to add this function to your code.

Enable hooks in your config/config.php

$config['enable_hooks'] = TRUE;


In your application/config/hooks.php add new hook on the "pre_system" call, which happens in core/CodeIgniter.php before the whole system runs.

$hook['pre_system'] = array(
    0 => array(         
        'function' => 'load_initial_functions',
        'filename' => 'your_hooks.php',
        'filepath' => 'hooks'
    )
);

Then in the hooks folder create 2 files:

First: application/hooks/your_functions.php and place your __autoload function and all other functions that you want available at this point.

Second: application/hooks/your_hooks.php and place this code:

function load_initial_functions()
{
    require_once(APPPATH.'hooks/your_functions.php');
}

This will make all of your functions defined in your_functions.php available everywhere in your code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!