本文整理自實戰經驗,涵蓋 Gii 代碼生成、模組配置、路由解析、存取控制、資料查詢與 URL 美化等核心主題。
yiic webapp /web/demo
protected/models/ 實際檔名一致,大小寫敏感。

Gii 產生模組時 Module ID 建議小寫。main.php 中配置:
'modules' => array(
'admin' => array(
'class' => 'application.modules.admin.AdminModule',
),
),
system → framework 目錄application → protected/application.modules.Admin.AdminModule → protected/modules/Admin/AdminModule.phppublic function accessRules() {
return array(
array('allow', 'actions' => array('index','view'), 'users' => array('*')),
array('allow', 'actions' => array('create','update'), 'users' => array('@')),
array('allow', 'actions' => array('admin','delete'), 'users' => array('admin')),
array('deny', 'users' => array('*')),
);
}
* 所有用戶,@ 已驗證用戶,admin 指定用戶名。
Yii::app()->user->id
public function getUrl() {
return Yii::app()->createUrl('post/view', array('id' => $this->id, 'title' => $this->title));
}
public function rules() {
return array(
array('news_title, news_content', 'required'),
array('news_title', 'length', 'max' => 128),
array('create_time, update_time', 'safe'), // 非表單欄位需加 safe
);
}
$this->render('view', array('time' => $time))public $time,視圖用 $this->timePost::model()->findAll(array(
'condition' => 'status=:status',
'params' => array(':status' => 1),
'order' => 'create_time DESC',
'limit' => 10,
));
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName' => false,
'rules' => array(
'posts' => 'post/list',
'post/' => 'post/view',
),
),
專案根目錄 .htaccess:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
class Banner extends CPortlet {
protected function renderContent() { $this->render('banner'); }
}
視圖中呼叫:widget('Banner'); ?>