DRY 原則: 重複代碼提取至 Library、Helper 或 Model。判斷標準:複製代碼時即為重構信號。
system 和 application 移至 Web 根目錄(public_html/webroot)之外。index.php 保留在 Web 根目錄,修改 $system_folder、$application_folder 為相對路徑。index.php、靜態資源(CSS/JS/圖片),隱藏框架核心代碼。<?php
// 生產環境 (index.php 或環境配置)
ini_set('display_errors', 'Off');
error_reporting(0);
define('MP_DB_DEBUG', false); // database.php 中 $db['default']['db_debug'] = MP_DB_DEBUG;
// 開發環境
ini_set('display_errors', 'On');
error_reporting(E_ALL);
define('MP_DB_DEBUG', true);
開發階段解決所有 Notice/Warning,上線前關閉顯示,啟用日志記錄(log_threshold)。
$this->input->post('key', TRUE) 啟用 XSS 清洗,或全局 $config['global_xss_filtering'] = TRUE(性能權衡)。set_rules('field', 'Label', 'trim|required|xss_clean|callback_custom')。html_escape($var) / htmlspecialchars()。SQL 注入: 僅使用 Active Record / Query Builder,禁止拼接 SQL。
CSRF: CI 3 內置 $this->security->get_csrf_hash(),表單隱藏域驗證。
SPAM: 限流(IP+時間)、CAPTCHA(CI 內置 captcha helper)。
$this->output->cache($minutes) 生成靜態文件。$this->db->cache_on() / cache_off() 緩存查詢結果。$this->cache->get()/save() (需 Cache 库) 緩存局部數據。<?php
// 禁止緩存(AJAX/動態頁)
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
$this->output->set_header("Pragma: no-cache");
// 長期緩存(靜態資源 CSS/JS/圖片)
$this->output->set_header('Cache-Control: public, max-age=2592000'); // 30天
$this->output->set_header('Expires: ' . gmdate('D, d M Y H:i:s', time()+2592000) . ' GMT');
<?php
// application/core/MY_Controller.php
class MY_Controller extends CI_Controller {
protected $data = [];
protected $tplExt = '.php';
protected $header = 'templates/header';
protected $footer = 'templates/footer';
public function __construct() {
parent::__construct();
$this->data['site_name'] = config_item('site_name');
// 開發環境開啟 Profiler
if (ENVIRONMENT === 'development') {
$this->output->enable_profiler(TRUE);
}
}
// 統一渲染方法
protected function _render($view, $data = []) {
$this->load->view($this->header, $this->data);
$this->load->view($view, array_merge($this->data, $data));
$this->load->view($this->footer);
}
}
子控制器繼承 MY_Controller,僅需 $this->_render('page/home') 即可自動套用 Header/Footer。
MY_Controller、MY_Model、MY_Loader 等 MY_* 前綴類放在 application/core/,自動替換系統同名類。MY_Form_validation 等擴展。index.php:定義常量、環境、引導文件。system/core/CodeIgniter.php:核心引導。
_display_cache),命中則直接輸出結束。CI_Controller(含 Loader)。Hooks 提供 8 個切入點(pre_system, pre_controller, post_controller_constructor 等)實現 AOP。
| 規範 | 說明 |
|---|---|
| 類名 | PascalCase,文件名同類名 User_model.php |
| 方法/變量 | snake_case |
| 數據庫表 | snake_case 複數 users |
| 視圖文件 | 小寫下劃線 user/profile.php |
| 配置項 | 小寫下劃線 $config['site_name'] |
| 縮進 | 4 空格,禁止 Tab |