Yii 框架以高效能、元件化著稱。本系列教程從目錄結構、入口文件、路由機制、視圖渲染、佈局模板開始,帶你快速上手 Yii 專案開發。
testyii/
├── framework/ # Yii 核心框架(手動放置)
├── protected/ # 應用程式核心(受保護目錄)
│ ├── components/ # 元件類別(Controller 基類等)
│ ├── controllers/ # 控制器
│ ├── models/ # 模型
│ ├── views/ # 視圖
│ │ ├── layouts/ # 佈局模板
│ │ ├── site/ # SiteController 對應視圖
│ │ └── ...
│ ├── config/ # 配置檔
│ │ ├── main.php # 主配置
│ │ └── ...
│ └── runtime/ # 執行時快取、日誌
├── index.php # 入口文件
└── .htaccess # URL 重寫規則
<?php
// 定義常數
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', 3);
// 載入框架
require_once($yii = dirname(__FILE__).'/framework/yii.php');
// 建立應用實例並執行
$config = require(dirname(__FILE__).'/protected/config/main.php');
Yii::createWebApplication($config)->run();
?>
關鍵點:Yii::createWebApplication() 建立全域 Yii::app() 物件,配置陣列鍵值自動綁定為物件屬性(如 Yii::app()->name)。
URL 格式:?r=Controller/Action 或 PATHINFO /Controller/Action
r 參數或 PATHINFOprotected/controllers/ControllerIDController.phpactionActionID()site(SiteController)index(actionIndex)/ 等同 ?r=site/index<?php
class SiteController extends Controller {
public function actionIndex() {
// 渲染視圖並套用佈局
$this->render('index');
// 僅渲染視圖內容(不套用佈局)
// $this->renderPartial('index');
}
}
?>
protected/views/site/index.phprender() 會套用佈局模板,renderPartial() 不會<?php
// protected/components/Controller.php
class Controller extends CController {
public $layout = '//layouts/column1'; // 對應 protected/views/layouts/column1.php
}
?>
佈局檔案中用 插入視圖內容。
protected/views/layouts/testlayout.phpController::$layout = '//layouts/testlayout';下一章將介紹 Gii 代碼生成器、模組開發與自訂模組。