一步一步重写 CodeIgniter 框架 (11) —— 使用 CodeIgniter 函数库

在完成了CI框架的类库扩展后,很自然我们就会想到函数库的扩展。函数库的扩展在 CI 中称为 helper 

函数与类有不同的地方,它不能继承,只能覆盖或者添加新的函数,或者直接完全新定义的一组函数。

由于扩展的方式与之前非常类似,下面直接用代码进行介绍

/**
     * Loader Helper
     *
     * This function loads the specified helper file.
     *
     * @param  mixed
     * @return void
     */
    public function helper($helpers = array()) {

        foreach ($this->_ci_prep_filename($helpers, '_helper') as $helper) {

            if ( isset($this->_ci_helpers[$helper])) {
                continue;
            }

            $ext_helper = APPPATH.'helpers/'.config_item('subclass_prefix').$helper.'.php';

            // 是否是个扩展
            if (file_exists($ext_helper)) {
                $base_helper = BASEPATH.'helpers/'.$helper.'.php';
                if ( ! file_exists($base_helper)) {
                    show_error('Unable to load the requested file: helpers/'.$helper.'.php');
                }

                include_once($ext_helper);
                include_once($base_helper);

                $this->_ci_helpers[$helper] = TRUE;
                log_message('debug', 'Helper loaded: '.$helper);
            }

            foreach ($this->_ci_helper_paths as $path) {
                if (file_exists($path.'helpers/'.$helper.'.php')) {
                    include_once($path.'helpers/'.$helper.'.php');

                    $this->_ci_helpers[$helper] = TRUE;
                    log_message('debug', 'Helper loaded: '.$helper);
                    break;
                }
            }

            // unable to load the helper
            if ( ! isset($this->_ci_helpers[$helper])) {
                show_error('Unable to load the requested file: helpers/'.$helper.'.php');
            }

        }

    }

上面的代码较为简单,

1)首先对加载的 helper 文件名进行预处理;

2) 然后判断是否存在“扩展”函数库, 存在的话则一起加载原始 函数库 和 扩展函数库;

3) 否则的话,只需要加载需要的文件就可以了,按照指定的路径顺序去搜索。

其中辅助函数 _ci_prep_filename 如下

function _ci_prep_filename($filename, $extension) {
        if ( ! is_array($filename)) {
            return array(strtolower(str_replace('.php', '', str_replace($extension, '', $filename)).$extension));
        } else {
            foreach ($filename as $key => $val) {
                $filename[$key] = strtolower(str_replace('.php', '', str_replace($extension, '', $filename)).$extension);
            }
            return $filename;
        }
    }
原文地址:https://www.cnblogs.com/zhenyu-whu/p/3286253.html