CodeIgniter (CI) 框架預設配置檔位於 application/config/,專案常需自定義配置(如 API 金鑰、業務常數、功能開關)。本文示範建立專屬配置檔、載入方式、多環境切換、最佳實踐。
路徑:application/config/expert.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* 專家系統配置
* @package AskExpert
*/
$config['expertid'] = [
'0' => '124',
'1' => '81',
'2' => '136'
];
// 更多配置範例
$config['api_timeout'] = 30;
$config['feature_flags'] = [
'new_ui' => true,
'beta_api' => false
];
$config['external_api'] = [
'endpoint' => 'https://api.example.com/v1',
'key' => env('EXPERT_API_KEY') // 搭配 phpdotenv 讀取 .env
];
?>
<?php
class Expert extends CI_Controller {
public function index() {
// 第 2 參數 TRUE:回傳配置陣列而非合併到全域 $this->config
$this->config->load('expert', TRUE);
// 讀取單一項(第 2 參數指定配置檔名稱)
$expertIds = $this->config->item('expertid', 'expert');
// 讀取整組配置
$allConfig = $this->config->item('expert');
var_dump($expertIds);
}
}
?>
編輯 application/config/autoload.php:
$autoload['config'] = ['expert']; // 不需第 2 參數 TRUE
之後任何地方直接 $this->config->item('expertid') 即可(無需指定檔名)。
CI 支援 ENVIRONMENT 常數(預設 development/production),建立對應目錄覆寫:
application/
├── config/
│ ├── expert.php # 基礎配置
│ ├── development/
│ │ └── expert.php # 開發環境覆寫(如測試 API Key)
│ └── production/
│ └── expert.php # 正式環境配置
development/expert.php 只需覆寫差異項:
<?php
$config['external_api']['key'] = 'dev_test_key_123';
$config['feature_flags']['beta_api'] = true;
?>
<?php
if (!function_exists('config_item_typed')) {
function config_item_typed($item, $index = '', $type = 'string', $default = null) {
$ci =& get_instance();
$val = $ci->config->item($item, $index);
if ($val === null) return $default;
switch ($type) {
case 'int': return (int)$val;
case 'float': return (float)$val;
case 'bool': return filter_var($val, FILTER_VALIDATE_BOOLEAN);
case 'array': return (array)$val;
default: return (string)$val;
}
}
}
// 使用
$timeout = config_item_typed('api_timeout', 'expert', 'int', 10);
?>
# .env(專案根目錄,.gitignore 忽略)
EXPERT_API_KEY=sk_live_xxxxxxxxxxxx
EXPERT_API_SECRET=whateversecret
# expert.php
$config['external_api']['key'] = getenv('EXPERT_API_KEY') ?: 'fallback_key';
搭配 vlucas/phpdotenv(Composer 安裝)在 index.php 最早處載入:
$dotenv = Dotenv\Dotenv::createImmutable(FCPATH);
$dotenv->load();
CI 3.x 無內建配置快取,可自行實作:
<?php
// core/MY_Config.php
class MY_Config extends CI_Config {
public function load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) {
$cacheKey = 'config_' . md5($file . $use_sections);
if (ENVIRONMENT === 'production' && ($cached = $this->cache->get($cacheKey))) {
return $cached;
}
$result = parent::load($file, $use_sections, $fail_gracefully);
if (ENVIRONMENT === 'production') {
$this->cache->save($cacheKey, $result, 3600);
}
return $result;
}
}
?>
| 現象 | 原因 | 解決 |
|---|---|---|
item() 回傳 NULL | 檔名拼錯、未載入、區段名稱錯誤 | 檢查 load() 參數、autoload.php、大小寫 |
| 合併到全域配置導致鍵名衝突 | 未使用 TRUE 區段模式 | 改用 $this->config->load('file', TRUE) 並指定區段名 |
| 環境覆寫不生效 | ENVIRONMENT 常數未正確設定 | 檢查 index.php define('ENVIRONMENT', ...) |
CI 自定義配置核心在於 $this->config->load('filename', TRUE) 區段模式,配合 環境目錄覆寫、.env 敏感值隔離、型別輔助函數、生產環境快取,即可構建清晰、安全、高效的配置管理體系。建議專案統一規範:config/{domain}.php 命名、敏感值絕不硬編碼、配置讀取集中在 Service/Repository 層而非 Controller 直接呼叫。