萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Yii Framework 學習筆記 (一):安裝、需求檢查、建立應用與偽靜態配置

Yii 簡介

Yii 是高效能、基於元件的 PHP5 框架,嚴格遵循 OOP、MVC、DAO/ActiveRecord、快取、RBAC、I18N/L10N 等企業級特性。透過 yiic 命令列工具快速生成專案骨架。

安裝步驟

  1. 下載 Yii 框架 (官網 yiiframework.com) 解壓至 Web 可存取目錄。
  2. 瀏覽 https://host/yii/requirements/index.php 檢查環境需求 (PDO、MBstring、GD 等)。結論顯示「滿足最低需求」即可。

建立第一個應用

$ cd /WebRoot/testdrive/framework
$ ./yiic webapp ../../testdrive
# 確認 Yes,自動生成目錄結構

生成目錄結構重點

testdrive/
├── index.php              # 入口腳本
├── protected/             # 受保護應用目錄 (不可直接 Web 存取)
│   ├── config/main.php    # 主配置
│   ├── controllers/       # 控制器
│   ├── models/            # 模型
│   ├── views/             # 視圖
│   └── runtime/           # 臨時檔案 (需可寫)
├── assets/                # 發佈資源 (CSS/JS/圖片)
├── css/, images/, themes/
└── yiic, yiic.php, yiic.bat

移除 URL 中的 index.php (偽靜態)

1. 配置 urlManager (protected/config/main.php)

<?php
return array(
    'components'=>array(
        'urlManager'=>array(
            'urlFormat'=>'path',
            'showScriptName'=>false, // 關鍵:隱藏 index.php
            'rules'=>array(
                'sites' => 'site/index',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
            ),
        ),
    ),
);

2. Apache .htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

3. Nginx 配置

server {
    root /www/mysite/htdocs;
    index index.php;
    location / {
        try_files $uri $uri/ /index.php?$args;
    }
    location ~ ^/(protected|framework|themes/\w+/views) { deny all; }
    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

驗證

瀏覽 https://host/testdrive/sites 應正確路由至 SiteController::actionIndex(),URL 中無 index.php。

下一步學習方向

  • 控制器/動作/視圖交互
  • 模型與 ActiveRecord
  • 表單驗證與 Widget
  • 使用者認證與 RBAC
copyright © 萬盛學電腦網 all rights reserved