前言
CodeIgniter 3 輕量靈活,但文檔分散。本文整理開發高頻使用的核心方法、載入方式、參數慣例與最佳實踐,作為日常開發速查手冊。
一、視圖載入與資料傳遞
| 方法 | 用途 | 範例 |
$this->load->view('name', $data, $return) | 載入視圖 | $this->load->view('user/profile', ['user'=>$user]) |
$this->load->view('name', $data, TRUE) | 回傳視圖字串 (不輸出) | $html = $this->load->view('email/template', $data, TRUE) |
$this->load->view('partials/header') | 載入局部視圖 (佈局中) | 在主視圖 <?php $this->load->view('partials/header'); ?> |
$this->load->view('name', $data, FALSE) | 直接輸出 (預設) | 同第一行 |
資料傳遞機制:$data 陣列鍵值自動 extract() 為視圖變數。
['title'=>'Hi', 'items'=>[1,2]] → 視圖中直接用 $title, $items。
二、資料庫 Query Builder 核心鏈式操作
// SELECT
$this->db->select('id, username, email')
->from('users')
->where('status', 1)
->where_in('role', ['admin', 'editor'])
->order_by('created_at', 'DESC')
->limit(20, 0)
->get()
->result_array(); // 回傳純陣列
// GET 編譯 SQL (除錯用)
$sql = $this->db->get_compiled_select('users');
echo $sql; // SELECT `id`, `username`, `email` FROM `users` WHERE `status` = 1 AND `role` IN ('admin','editor') ORDER BY `created_at` DESC LIMIT 20
// INSERT
$data = ['username'=>'john', 'email'=>'john@example.com', 'created_at'=>date('Y-m-d H:i:s')];
$this->db->insert('users', $data);
$insert_id = $this->db->insert_id();
// UPDATE
$this->db->where('id', 10)
->update('users', ['last_login'=>date('Y-m-d H:i:s')]);
// DELETE
$this->db->where('last_login <', '2020-01-01')
->delete('users');
// 批次插入
$batch = [
['username'=>'a', 'email'=>'a@b.c'],
['username'=>'b', 'email'=>'b@c.d'],
];
$this->db->insert_batch('users', $batch);
// 事務
$this->db->trans_start();
$this->db->insert('orders', $order);
$this->db->insert('order_items', $items);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) { /* 回滾已自動執行 */ }
// 原生查詢 (參數綁定防注入)
$sql = "SELECT * FROM users WHERE email = ? AND status = ?";
$query = $this->db->query($sql, [$email, 1]);
$rows = $query->result_array();
三、模型載入與 CI 實例獲取
// 載入模型 (第二參數別名,第三參數自動連線資料庫)
$this->load->model('User_model', 'user', TRUE);
// 使用
$this->user->get_by_id(1);
// 在模型/庫/輔助函數中獲取 CI 超級物件
$CI =& get_instance();
$CI->db->query(...);
$CI->load->library('session');
$CI->config->item('base_url');
四、常用輔助函數載入與函數
| 輔助函數 | 載入 | 常用函數 |
| URL | $this->load->helper('url') | base_url(), site_url(), current_url(), redirect(), anchor() |
| 表單 | $this->load->helper('form') | form_open(), form_input(), form_dropdown(), set_value(), form_error() |
| HTML | $this->load->helper('html') | img(), link_tag(), script_tag(), ul(), ol() |
| 字串 | $this->load->helper('string') | random_string(), reduce_multiples(), quote() |
| 檔案 | $this->load->helper('file') | read_file(), write_file(), delete_files(), get_filenames() |
| 日期 | $this->load->helper('date') | now(), human_to_unix(), unix_to_human(), timespan() |
| 安全 | $this->load->helper('security') | xss_clean(), csrf_verify(), get_csrf_hash(), do_hash() |
| 陣列 | $this->load->helper('array') | element(), elements(), random_element() |
五、Session、Cookie、加密、驗證
// Session (需先 $this->load->library('session'))
$this->session->set_userdata('user_id', 1001);
$user_id = $this->session->userdata('user_id');
$this->session->set_flashdata('msg', '操作成功'); // 單次請求後自動刪除
$msg = $this->session->flashdata('msg');
// Cookie
$this->load->helper('cookie');
set_cookie('pref_theme', 'dark', 86400*30); // 30 天
$theme = get_cookie('pref_theme');
delete_cookie('pref_theme');
// 加密庫 (需配置 encryption_key)
$this->load->library('encryption');
$encrypted = $this->encryption->encrypt('secret data');
$decrypted = $this->encryption->decrypt($encrypted);
// 表單驗證
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[8]');
if ($this->form_validation->run() === FALSE) {
// 失敗
echo validation_errors();
} else {
// 成功
}
六、輸出、快取、基準測試、鉤子
| 功能 | 方法/類別 | 範例 |
| 輸出控制 | $this->output | $this->output->set_content_type('application/json')->set_output(json_encode($data)) |
| 頁面快取 | $this->output->cache($minutes) | $this->output->cache(60); (僅限非動態頁面) |
| 基準測試 | $this->benchmark | $this->benchmark->mark('start'); ... $this->benchmark->mark('end'); echo $this->benchmark->elapsed_time('start', 'end'); |
| 鉤子 | $this->hooks | 配置 application/config/hooks.php,啟用 $config['enable_hooks'] = TRUE |
七、核心類擴展與自訂庫
1. 擴展核心控制器 application/core/MY_Controller.php
<?php
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
// 共用初始化:載入資料庫、Session、通用模型、設定時區
date_default_timezone_set('Asia/Taipei');
$this->load->model('common/Setting_model', 'setting');
}
// 共用方法
public function render($view, $data = []) {
$this->load->view('templates/header', $data);
$this->load->view($view, $data);
$this->load->view('templates/footer');
}
}
2. 擴展核心模型 application/core/MY_Model.php
<?php
class MY_Model extends CI_Model {
protected $table;
protected $primary_key = 'id';
public function get($id) { return $this->db->get_where($this->table, [$this->primary_key => $id])->row_array(); }
public function get_all($where = [], $limit = 0, $offset = 0) { return $this->db->get_where($this->table, $where, $limit, $offset)->result_array(); }
public function insert($data) { $this->db->insert($this->table, $data); return $this->db->insert_id(); }
public function update($id, $data) { return $this->db->where($this->primary_key, $id)->update($this->table, $data); }
public function delete($id) { return $this->db->where($this->primary_key, $id)->delete($this->table); }
}
3. 自訂庫 application/libraries/Payment.php
<?php
class Payment {
protected $ci;
public function __construct() { $this->ci =& get_instance(); }
public function charge($order_id, $amount) { /* ... */ }
}
// 控制器使用
$this->load->library('payment');
$this->payment->charge(123, 99.9);
八、路由、URI、輸入、安全
| 功能 | 方法 | 範例 |
| 路由配置 | application/config/routes.php | $route['products/(:num)'] = 'catalog/detail/$1'; |
| URI 片段 | $this->uri->segment(n) | $id = $this->uri->segment(3); |
| GET/POST 取值 | $this->input->get('key'), $this->input->post('key') | $kw = $this->input->get('q', TRUE); (第二參數 XSS 過濾) |
| IP 取得 | $this->input->ip_address() | 自動處理代理 Header |
| User Agent | $this->input->user_agent() | |
| CSRF 保護 | 配置 $config['csrf_protection'] = TRUE | 表單自動包含 <?= csrf_field() ?> |
九、自動載入配置 application/config/autoload.php
$autoload['libraries'] = ['database', 'session', 'form_validation', 'encryption', 'CISmarty'];
$autoload['helper'] = ['url', 'form', 'html', 'string', 'date', 'security', 'array', 'cookie', 'file'];
$autoload['model'] = ['common/Setting_model'];
$autoload['config'] = ['smarty', 'redis', 'custom'];
$autoload['language'] = [];
$autoload['driver'] = ['cache'];
十、常見坑與避雷指南
$this->db->where('col', NULL) 產生 WHERE col = '' → 用 where('col IS NULL', NULL, FALSE)
redirect() 預設 location 模式在 CLI/測試失效 → 指定 redirect('/', 'refresh')
- 視圖變數未定義產生 Notice → 視圖前用
isset($var) ? $var : '' 或控制器預設 $data['var'] = ''
- 批次操作
insert_batch/update_batch 記得分塊 (每 100 條) 避免 SQL 過長
- 生產環境關閉
$config['log_threshold'] = 1, $config['db_debug'] = FALSE, $config['save_queries'] = FALSE
總結
熟練掌握 **視圖載入、Query Builder 鏈式操作、模型/庫/輔助函數載入、Session/驗證/加密、核心類擴展 (MY_Controller/MY_Model)、自動載入配置** 這 10 大類高頻方法,即可覆蓋 90% 的 CI 3 日常開發場景。建議將本表格匯出為 PDF/Markdown 置於專案 docs/ 目錄,團隊共享維護。