PHP CodeIgniter框架项目实战:一步步打造企业级应用
短信预约 -IT技能 免费直播动态提醒
环境搭建
- 安装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
即可看到项目运行效果。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341