CodeIgniter (CI) 是輕量級 PHP 框架,採用 MVC 架構,學習曲線平緩。本教程從零開始構建一個「信息發布」小系統,涵蓋路由、控制器、模型、視圖、Active Record、表單驗證等核心概念。
application/
├── config/ # 配置文件(database.php, routes.php)
├── controllers/ # 控制器:邏輯判斷、協調 M/V
├── models/ # 模型:資料庫操作
├── views/ # 視圖:HTML 模板
└── helpers/ # 輔助函數
$this->load->view('file', $data) 接收變量application/config/database.php$db['default'] = [
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'test',
'dbdriver' => 'mysqli',
'dbprefix' => 'ts_',
'charset' => 'utf8',
'dbcollat' => 'utf8_general_ci',
];
application/config/routes.php$route['default_controller'] = 'test/home'; // 訪問 / 直接進入 Test::home()
URL 格式:https://domain/index.php/控制器/方法(可通過 .htaccess 隱藏 index.php)。
load->view('home');
}
}
// application/views/home.php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>Home</title></head>
<body>
<h1>這是我們的主頁</h1>
</body></html>
ts_newsCREATE TABLE ts_news (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(200) NOT NULL,
content TEXT NOT NULL,
update_time INT NOT NULL,
create_time INT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
application/models/News_model.phpload->database();
}
public function insert($data, $table = 'news') {
$this->db->insert($table, $data);
return $this->db->affected_rows() > 0 ? $this->db->insert_id() : FALSE;
}
}
add_news()public function __construct() {
parent::__construct();
$this->load->helper('url'); // site_url()
$this->load->model('news_model');
}
public function add_news() {
$title = $this->input->get('title', TRUE); // XSS 過濾
$content = $this->input->get('content');
// 簡單驗證
if (strlen($title) < 20 || strlen($content) < 20) {
echo '標題或正文內容過短'; return;
}
$data = [
'id' => '', 'title' => $title, 'content' => $content,
'update_time' => time(), 'create_time' => time()
];
if ($this->news_model->insert($data, 'news')) {
redirect('test/home'); // PRG 模式避免重複提交
} else {
echo '提交失敗';
}
}
<form action="<?= site_url('test/add_news') ?>" method="get">
<label>標題</label><input type="text" name="title"><br>
<label>正文</label><textarea name="content" cols="30" rows="10"></textarea><br>
<input type="submit" value="提交">
</form>
get_all()public function get_all($table) {
return $this->db->get($table)->result_array();
}
home() 傳遞數據public function home() {
$data['news'] = $this->news_model->get_all('news');
$this->load->view('home', $data);
}
<?php foreach ($news as $item): ?>
<div>
<h3><?= $item['title'] ?></h3>
<span>發布時間:<?= date('Y-m-d H:i:s', $item['create_time']) ?></span>
<p><?= $item['content'] ?></p>
</div>
<?php endforeach; ?>
| 概念 | CI 實作 | 關鍵方法 |
|---|---|---|
| 載入視圖 | $this->load->view() | view('file', $data, true/false) |
| 獲取輸入 | Input 類 | $this->input->get/post('key', xss_clean) |
| 生成 URL | URL Helper | site_url('c/m'), base_url('path') |
| 重導向 | URL Helper | redirect('c/m') |
| 資料庫操作 | Active Record | $this->db->get/insert/update/delete |
| 防 XSS | Input 類 / 輸出轉義 | $this->input->get('key', TRUE) |
form_validation 替換手寫驗證pagination 處理大量列表index.php