CodeIgniter
技术栈
后端框架
phplightweightmvcfastsmall-footprint安装
1. 环境准备
- OS:Linux / macOS / Windows
- PHP:>= 7.4(CI3),>= 8.1(CI4)
- PHP 扩展:intl, mbstring, json, mysqlnd(数据库可选)
- Composer:最新稳定版(CI4)或手动下载(CI3)
- 数据库:MySQL 5.1+ / PostgreSQL / SQLite3
2. 安装命令
CodeIgniter 4(推荐)
# 通过 Composer
composer create-project codeigniter4/appstarter my-app
# 或手动下载
wget https://github.com/codeigniter4/CodeIgniter4/archive/refs/tags/v4.4.5.zip
unzip v4.4.5.zip
CodeIgniter 3
# 手动下载
wget https://github.com/bcit-ci/CodeIgniter/archive/refs/tags/3.1.13.zip
unzip 3.1.13.zip
启动开发服务器
cd my-app
php spark serve
# 访问 http://localhost:8080
3. 常见安装问题
CI4 环境文件
# 开发模式下复制 .env
cp env .env
# 设置为 development 模式
# CI_ENVIRONMENT = development
# 生成密钥
php spark key:generate
目录权限
chmod -R 775 writable/
"No input file specified"
确保 public/.htaccess 存在且 mod_rewrite 已启用。
国内镜像
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
示例
Hello World:CodeIgniter 4 控制器
目标
创建 CI4 控制器,展示路由定义和 JSON 响应。
完整代码
1. 编辑 app/Controllers/Hello.php
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\ResponseInterface;
class Hello extends BaseController
{
public function index(): ResponseInterface
{
return $this->response->setJSON([
'message' => 'Hello, Vibe!',
'framework' => 'CodeIgniter',
'php_version' => PHP_VERSION,
'timestamp' => date('c'),
]);
}
public function greet(string $name): ResponseInterface
{
return $this->response->setJSON([
'message' => "Hello, {$name}!",
'powered_by' => 'CodeIgniter 4',
]);
}
}
2. 编辑 app/Config/Routes.php
<?php
use CodeIgniter\Router\RouteCollection;
/** @var RouteCollection $routes */
$routes->get('hello', 'Hello::index');
$routes->get('hello/(:segment)', 'Hello::greet/$1');
运行步骤
php spark serve
# 访问 http://localhost:8080/hello
预期输出
curl http://localhost:8080/hello
# {"message":"Hello, Vibe!","framework":"CodeIgniter","php_version":"8.2.0","timestamp":"2024-01-01T00:00:00+00:00"}
curl http://localhost:8080/hello/World
# {"message":"Hello, World!","powered_by":"CodeIgniter 4"}
教程
CodeIgniter 4 入门教程:CRUD 新闻应用
1. 背景
CodeIgniter 以轻量和速度著称。本教程带你构建完整的新闻 CRUD 应用,掌握 CI4 的 MVC 模式、模型、查询构建器和表单。
2. 前置概念
| 概念 | 说明 |
|---|---|
| Model | CodeIgniter\Model,内置 CRUD 方法 |
| Entity | 实体对象,属性可自动转换类型 |
| Validation | 模型内 $validationRules 定义 |
| Routing | 自动/手动路由映射 |
3. 分步操作
步骤一:创建数据库
CREATE TABLE news (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
slug VARCHAR(255) NOT NULL UNIQUE,
body TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
配置 app/Config/Database.php:
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'codeigniter_demo',
'DBDriver' => 'MySQLi',
];
步骤二:创建模型
php spark make:model News
编辑 app/Models/NewsModel.php:
<?php
namespace App\Models;
use CodeIgniter\Model;
class NewsModel extends Model
{
protected $table = 'news';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $allowedFields = ['title', 'slug', 'body'];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $validationRules = [
'title' => 'required|min_length[3]|max_length[255]',
'body' => 'required|min_length[10]',
];
}
步骤三:创建控制器
php spark make:controller News
<?php
namespace App\Controllers;
use App\Models\NewsModel;
use CodeIgniter\HTTP\ResponseInterface;
class News extends BaseController
{
public function index(): string
{
$model = new NewsModel();
$data['news'] = $model->orderBy('id', 'DESC')->findAll();
return view('news/index', $data);
}
public function create(): string
{
return view('news/create');
}
public function store(): ResponseInterface
{
$model = new NewsModel();
$data = [
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', true),
'body' => $this->request->getPost('body'),
];
if ($model->insert($data)) {
return redirect()->to('/news')->with('success', 'News created!');
}
return redirect()->back()->withInput()->with('errors', $model->errors());
}
public function edit(int $id): string
{
$model = new NewsModel();
$data['news'] = $model->find($id);
return view('news/edit', $data);
}
public function update(int $id): ResponseInterface
{
$model = new NewsModel();
$data = [
'title' => $this->request->getPost('title'),
'body' => $this->request->getPost('body'),
];
$model->update($id, $data);
return redirect()->to('/news')->with('success', 'Updated!');
}
public function delete(int $id): ResponseInterface
{
(new NewsModel())->delete($id);
return redirect()->to('/news')->with('success', 'Deleted!');
}
}
步骤四:路由
app/Config/Routes.php:
$routes->get('news', 'News::index');
$routes->get('news/create', 'News::create');
$routes->post('news', 'News::store');
$routes->get('news/edit/(:num)', 'News::edit/$1');
$routes->post('news/(:num)', 'News::update/$1');
$routes->get('news/delete/(:num)', 'News::delete/$1');
4. 验证
php spark serve
curl -X POST http://localhost:8080/news \
-d "title=CI4 News&body=CodeIgniter 4 is amazing!"
curl http://localhost:8080/news
5. 思考题
- 如何使用 Entity 类为 News 添加 getExcerpt() 方法?
- 如何启用 CI4 的自动路由简化路由定义?
- 如何为 News 添加分页功能?
参考资料
- [1] CodeIgniter Foundation. CodeIgniter 4 Documentation. 2024. https://codeigniter.com/user_guide
- [2] Lonnie Ezell. CodeIgniter 4: Build Complete Web Applications. 2021.
- [3] CodeIgniter Team. CodeIgniter GitHub Repository. 2024. https://github.com/codeigniter4/CodeIgniter4