php中自定义自动加载函数

来源:互联网 发布:属于淘宝禁售商品刀 编辑:程序博客网 时间:2024/04/28 15:14
//在php中 如何使用自动加载,不用在调用某个类的时候,去require_once('所需要类的地址')

//定义自己的自动加载函数

class AutoLoad{
public function __construct(){
 spl_autoload_register(array($this, 'autoLoad'));
}
pulblic static function autoLoad($class_name){


$app_domain = AppDomain::get();
        if(!$app_domain){
            trigger_error('Must define the APP_DOMAIN in the entry!', E_USER_ERROR);
        }
        $app_cls_domain_arr = explode('_', $app_domain);
        $app_cls_domain = $app_cls_domain_arr[0];
        $ap_key_fmt = "class_%s_{$className}_location";
        $class_domain_arr = array($app_cls_domain, 'common');
        $file_path = null;
        $apc_loaded = extension_loaded('apc');
        if($apc_loaded){
            foreach($class_domain_arr as $domain){ 
                $ap_key_str = sprintf($ap_key_fmt, $domain);
                if($file_path = apc_fetch($ap_key_str)){
                    break;
                }
            }
        }
        if(is_file($file_path)){
           require_once($file_path);    
           return true;
        } 
        //这里要提前规定好 你存放一些class类的地址,然后才好去寻找
        // find class in the app class or common dir
        $app_class_dir = GLOBAL_BASE_PATH . 'classes/apps/' . $app_cls_domain;
        $common_class_dir = GLOBAL_BASE_PATH . 'classes/common';
        $class_dir_arr = array($app_class_dir, $common_class_dir);
        $class_dir_arr_assoc = array_combine($class_domain_arr, $class_dir_arr);
        foreach($class_dir_arr_assoc as $domain=>$dir){
            $class_real_dir = realpath($dir);
            $cls_file_name = $className . '.php';
            $key = array_search($cls_file_name, scandir($class_real_dir));
            $file_path = $class_real_dir . '/' . ($key === false ? null : $cls_file_name);
            if(is_file($file_path)){
                if($apc_loaded){
                    $ap_key_str = sprintf($ap_key_fmt, $domain);
                    apc_store($ap_key_str, $file_path);
                }
                require_once($file_path); 
                return true;
            } 
        }
        return false;
}
}

原创粉丝点击