在完成了CI框架的類庫擴展後,很天然咱們就會想到函數庫的擴展。函數庫的擴展在 CI 中稱爲 helper php
函數與類有不一樣的地方,它不能繼承,只能覆蓋或者添加新的函數,或者直接徹底新定義的一組函數。框架
因爲擴展的方式與以前很是相似,下面直接用代碼進行介紹函數
/** * 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'); } } }
上面的代碼較爲簡單,this
1)首先對加載的 helper 文件名進行預處理;spa
2) 而後判斷是否存在「擴展」函數庫, 存在的話則一塊兒加載原始 函數庫 和 擴展函數庫;debug
3) 不然的話,只須要加載須要的文件就能夠了,按照指定的路徑順序去搜索。code
其中輔助函數 _ci_prep_filename 以下blog
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; } }