2013-07-21

Yii 筆記 1 (建立 webapp)

下載 yii 並解壓縮到 web server 的 DocumentRoot。以 Yii 的 requirements 檢查環境是否符合需求 http://localhost/yii-1.1.13/requirements/

利用 yiic 建立 webapp
c:\wamp\www\yii-1.1.13\framework>yiic webapp .\..\..\yiitest01

建立的 webapp 並沒有包含 Yii framework, 可以將 c:\wamp\www\yii-1.1.13\framework 複製到 yiitest01/ 裡。然後修改 index.php 裡 $yii 的 framework 路徑。

到 protected/config/main.php 開啟 gii module 設定
 'modules'=>array(
  'gii'=>array(
   'class'=>'system.gii.GiiModule',
   'password'=>'密碼',
   // If removed, Gii defaults to localhost only. Edit carefully to taste.
   'ipFilters'=>array('127.0.0.1','::1'),
  ),
 ),

連到 http://localhost/yiitest01/index.php?r=gii 輸入密碼後,可以看到 gii 預設的功能選單,包含:Controller Generator、Crud Generator、Form Generator、Model Generator、Module Generator。

點選 Controller Generator,在 Controller ID 欄填入 message,Action IDs 欄填入 hello(預設為 index),接著按 "preview" 按鈕,將產生兩個檔案:
controllers\MessageController.php
views\message\hello.php
點按 "Generate" 按鈕,以產生檔案。

點按 "try it now" 時,由於沒有 index action 所以會得到 404
http://localhost/yiitest01/index.php?r=message    // 得到 404
http://localhost/yiitest01/index.php?r=message/hello    // 得到正常頁面

查看 MessageController.php
class MessageController extends Controller
{
    public function actionHello()
    {
        $this->render('hello');
    }
}

也可以設定某個 action 為 default action
public $defaultAction = 'hello';

在 View 裡,變數對應的關係:
$this    // controller object
$this->id    // controller id
$this->action->id    // action id
echo CHtml::link('連結字串', array('控制器/動作')); // 顯示連結

沒有留言:

FB 留言