xmall/ (專案根目錄)
├── index.php # 入口檔
├── Conf/
│ └── config.php # 專案配置
├── Lib/
│ ├── Action/ # 控制器目錄
│ │ └── TestAction.class.php
│ └── Model/ # 模型目錄
│ └── UserModel.class.php
└── Tpl/
└── default/ # 主題目錄
└── Test/ # 模組模板目錄
└── test.html
檔案:Lib/Action/TestAction.class.php
<?php
class TestAction extends Action {
public function index() {
// 直接渲染 Tpl/default/Test/test.html
$this->display('test');
}
public function testModel() {
// D() 載入自定義 Model
$m = D('User');
echo $m->test();
}
}
關鍵點:
Action 後綴display('test') 不需副檔名,自動尋找 test.html (或配置後綴)/Test/index (T 大寫)檔案:Tpl/default/Test/test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>測試頁面</title>
</head>
<body>
<h1>Hello ThinkPHP!</h1>
<p>當前時間:<?php echo date('Y-m-d H:i:s'); ?></p>
</body>
</html>
檔案:Lib/Model/UserModel.class.php
<?php
class UserModel extends Model {
public function test() {
return '123456';
}
// 實際專案常用方法
public function getUserById($id) {
return $this->where(['id' => $id])->find();
}
}
命名規範:類名 = 模型名 + Model,檔案名同類名。調用時 D('User') 區分大小寫。
檔案:Conf/config.php
<?php
return [
// 開啟除錯 (開發階段必開)
'APP_DEBUG' => true,
// 預設主題
'DEFAULT_THEME' => 'default',
// URL 不區分大小寫 (可選,預設區分)
'URL_CASE_INSENSITIVE' => true,
// 模板後綴 (可選)
'TMPL_TEMPLATE_SUFFIX' => '.html',
];
檔案:index.php
<?php
define('APP_DEBUG', true); // 除錯常數
define('APP_PATH', './xmall/'); // 專案路徑
require './ThinkPHP/ThinkPHP.php'; // 框架入口
| 訪問 URL | 預期結果 |
|---|---|
https://localhost/xmall/index.php/Test/index | 顯示 test.html 內容 |
https://localhost/xmall/index.php/Test/testModel | 輸出 123456 |
| 錯誤現象 | 原因 | 解決 |
|---|---|---|
| 404 / Class 'TestAction' not found | 檔案名/類名大小寫不符、目錄錯誤 | 確認 Lib/Action/TestAction.class.php、類名 TestAction |
| Template not exists | 模板路徑不符合定位規則 | 檢查 Tpl/default/Test/test.html、DEFAULT_THEME 設定 |
| Model 'User' not found | 模型檔案/類名錯誤 | 確認 Lib/Model/UserModel.class.php、D('User') 大小寫 |
| 頁面空白/報錯無輸出 | 未開啟 APP_DEBUG | 入口檔與 config.php 雙重開啟除錯 |
大型專案可啟用分組:
// config.php 'APP_GROUP_LIST' => 'Home,Admin,Api', 'DEFAULT_GROUP' => 'Home',
目錄結構調整為:
Lib/
├── Action/
│ ├── Home/
│ │ └── IndexAction.class.php
│ └── Admin/
│ └── IndexAction.class.php
└── Model/
├── Home/
│ └── UserModel.class.php
└── Admin/
└── UserModel.class.php
Lib/Action/*Action.class.php → 繼承 ActionLib/Model/*Model.class.php → 繼承 ModelTpl/主題/模組/操作.html → display() 渲染APP_DEBUG、DEFAULT_THEME、URL_CASE_INSENSITIVE掌握此流程,即可快速建構符合 ThinkPHP 規範的 MVC 架構專案。