文章目录
-
- 步骤
-
- .env配置管理(不是虚拟环境)
-
- .env和database.config哪个优先级高?
- [.sample.env .env样板](#.sample.env .env样板)
it发展到现在,php当然也有各种框架,thinkphp用的就比较多。
步骤
前提:
php、composer都已装好,php.ini已配置好(包括扩展等都已放开),mysql已安装好。
1、创建项目
bash
带目录创建:
composer create-project topthink/think 具体的项目名
如果已有目录,进入到目录内,用如下命令创建:
composer create-project topthink/think ./
2、创建文件app/controller/User.php,代码:
php
<?php
declare (strict_types = 1);
namespace app\controller;
use app\BaseController;
use think\facade\View; // 引入 View facade
class User extends BaseController
{
/**
* 显示资源列表
*/
public function index()
{
// 1. 模拟一些数据(因为还没连数据库)
$mockData = [
['id' => 1, 'name' => '张三', 'email' => 'zhangsan@example.com', 'create_time' => date('Y-m-d H:i:s')],
['id' => 2, 'name' => '李四', 'email' => 'lisi@example.com', 'create_time' => date('Y-m-d H:i:s')],
['id' => 3, 'name' => '王五', 'email' => 'wangwu@example.com', 'create_time' => date('Y-m-d H:i:s')],
];
// 2. 将数据赋值给模板变量 'users'
View::assign('users', $mockData);
// 3. 渲染 view/user/index.html 模板
return View::fetch('index');
}
/**
* 显示创建资源表单页.
*/
public function create()
{
return 'Create User Page';
}
}
3、创建view/user/index.html,代码:
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
tr:nth-child(even) { background-color: #f9f9f9; }
</style>
</head>
<body>
<h1>用户管理中心</h1>
<!-- 如果 users 变量存在且不为空 -->
{notempty name="users"}
<table>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
<th>创建时间</th>
</tr>
</thead>
<tbody>
<!-- 循环遍历 users 数组 -->
{foreach $users as $user}
<tr>
<td>{$user.id}</td>
<td>{$user.name}</td>
<td>{$user.email}</td>
<td>{$user.create_time}</td>
</tr>
{/foreach}
</tbody>
</table>
{else /}
<p>暂无用户数据,请先添加用户。</p>
{/notempty}
<br>
<a href="/user/create">添加新用户</a>
</body>
</html>
4、config/database.php配置数据库
数据库名、账号密码等。
5、启动项目
bash
php think run
6、浏览器访问http://localhost:8000/user,出现用户信息表示成功。
.env配置管理(不是虚拟环境)
php中的.env只是配置管理,不是虚拟环境。
.env是比较有用的,例如:
APP_DEBUG = true # 开启debug后,f12可以看到报错信息。
.env和database.config哪个优先级高?
.env优先级高。
.sample.env .env样板
bash
APP_DEBUG = true
DB_TYPE = mysql
DB_HOST = 127.0.0.1
DB_NAME = test
DB_USER = username
DB_PASS = password
DB_PORT = 3306
DB_CHARSET = utf8
DEFAULT_LANG = zh-cn