首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

CodeIgniter $this->load->library() 完整用法解析與進階技巧

     編輯:PHP 綜合知識

$this->load->library() 是 CodeIgniter 載入類別庫 (Libraries) 的核心方法,掌握其完整參數與行為,能靈活管理依賴、避免命名衝突、實現條件式載入。本文系統整理官方文件未盡詳述的進階用法。

一、基本語法與三個參數

$this->load->library($library, $params = NULL, $object_name = NULL);
參數型別說明
$librarystring類別名稱 (不含副檔名),大小寫不敏感,會自動對應 application/libraries/ 下同名檔案 (首字大寫)。
$paramsarray建構子參數陣列,將以 new Library($params) 傳入。
$object_namestring自訂物件屬性名稱,預設為類別名稱小寫 (如 Email → $this->email)。

二、核心規則與命名慣例

  1. 檔名 = 類別名:Myclass.php → class Myclass (首字大寫)。
  2. 存放位置:application/libraries/ (專案專用) 或 system/libraries/ (核心擴展)。
  3. 子目錄支援:$this->load->library('folder/Myclass') 對應 libraries/folder/Myclass.php。

三、進階用法範例

1. 傳遞建構子參數 (如 Email 設定)

$config = [
    'protocol' => 'smtp',
    'smtp_host' => 'ssl://smtp.gmail.com',
    'smtp_port' => 465,
    'smtp_user' => 'user@gmail.com',
    'smtp_pass' => 'app_password',
    'charset' => 'utf-8',
    'mailtype' => 'html',
];
$this->load->library('email', $config);

2. 自訂物件名稱 (避免衝突/語意化)

$this->load->library('session', '', 'my_session');
// 使用:$this->my_session->set_userdata('key', 'val');

3. 子目錄載入

$this->load->library('payment/Alipay'); // libraries/payment/Alipay.php

4. 條件式/延遲載入 (效能優化)

if ($this->input->post('need_pdf')) {
    $this->load->library('Pdf'); // 僅在需要時載入
}

四、自動載入設定 (application/config/autoload.php)

$autoload['libraries'] = ['database', 'session', 'email', 'Myauth'];

注意: 自動載入無法傳遞 $params、$object_name;需參數時請在 Controller 建構子手動載入。

五、常見錯誤與除錯

Unable to load the requested class: Xxx
1. 檔名/類別名大小寫不符 (Linux 區分大小寫)。
2. 檔案未放在 libraries/。
3. 類別未定義 class Xxx 或命名空間錯誤 (CI 3 不支援 NS)。
Property "$this->xxx" undefined
自訂 $object_name 但使用預設名稱,或拼字錯誤。
重複載入導致資源浪費
CI 內部有單例快取,同一請求多次載入同一 Library 會回傳同一實例;若需全新實例,請自行 new Library()。

六、最佳實踐建議

  • 自訂 Library 繼承 CI_Library (可選) 以取得 $this->ci =& get_instance() 存取 CI 超級物件。
  • 建構子型別提示:public function __construct(array $config = [])。
  • 將可重用設定寫入 config/xxx.php,Library 內 $this->ci->config->load('xxx') 讀取,減少 Controller 參數傳遞。
  • 命名建議:Myauth、PdfGenerator、ApiClient (PascalCase),避免與核心庫衝突。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved