环境搭建
- 安装PHP
CodeIgniter框架需要PHP 5.6或更高版本的支持,因此首先需要安装PHP。可以从PHP官网下载并安装。
- 安装Composer
Composer是PHP的包管理器,可以方便地安装和管理CodeIgniter框架和其它依赖。可以从Composer官网下载并安装。
- 创建项目
使用Composer创建CodeIgniter项目:
composer create-project codeigniter4/app-starter-kit
数据库连接
在application/config/database.php
文件中配置数据库连接信息:
$db["default"] = [
"DSN" => "",
"hostname" => "localhost",
"username" => "root",
"password" => "",
"database" => "codeigniter_db",
"DBDriver" => "MySQLi",
"DBPrefix" => "ci_",
"pConnect" => FALSE,
"DBDebug" => (ENVIRONMENT !== "production"),
"cacheOn" => FALSE,
"cacheDir" => "",
"charset" => "utf8",
"DBCollat" => "utf8_general_ci",
"swapPre" => "",
"encrypt" => FALSE,
"compress" => FALSE,
"strictOn" => FALSE,
"failover" => [],
"port" => 3306,
];
路由配置
在application/Config/Routes.php
文件中配置路由规则:
$routes->get("/", "Home::index");
$routes->get("/users", "Users::index");
$routes->get("/users/create", "Users::create");
$routes->post("/users", "Users::store");
$routes->get("/users/:id/edit", "Users::edit/$1");
$routes->put("/users/:id", "Users::update/$1");
$routes->delete("/users/:id", "Users::delete/$1");
控制器编写
在application/Controllers
目录下创建控制器文件Home.php
:
<?php
namespace AppControllers;
use CodeIgniterController;
class Home extends Controller
{
public function index()
{
return view("home", [
"title" => "CodeIgniter 4 App",
"content" => "This is the home page."
]);
}
}
模型设计
在application/Models
目录下创建模型文件User.php
:
<?php
namespace AppModels;
use CodeIgniterModel;
class User extends Model
{
protected $table = "users";
protected $primaryKey = "id";
protected $allowedFields = ["name", "email", "password"];
protected $returnType = "AppEntitiesUser";
protected $useTimestamps = true;
}
视图渲染
在application/Views
目录下创建视图文件home.php
:
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<h1><?php echo $content; ?></h1>
</body>
</html>
运行项目
使用以下命令运行项目:
php spark serve
然后打开浏览器访问http://localhost:8080
即可看到项目运行效果。