適合:**企業級專案、API 服務、多輸出格式需求、重視架構規範的團隊**。
composer create-project agavi/agavi myproject "~1.0"
cd myproject
# 產生專案骨架
./bin/agavi project-create
目錄結構:
myproject/ ├── app/ # 應用程式核心 │ ├── config/ # 路由、資料庫、驗證、快取等設定 │ ├── modules/ # 模組 (Default, Admin, Api...) │ │ └── Default/ │ │ ├── actions/ # Action 類別 │ │ ├── views/ # View 類別 + 模板 │ │ ├── templates/ # .php 模板檔 │ │ └── config/ # 模組級路由、驗證 │ ├── lib/ # 共用類別、Model、Service │ └── templates/ # 全域母版頁 ├── pub/ # 公開資產 (CSS, JS, 圖片) ├── bin/agavi # CLI 工具 └── vendor/
# 互動式產生
./bin/agavi action-wizard
# Module name: Default
# Action name: Hello
# Views: Success
產生檔案:
<?php
// app/modules/Default/actions/HelloAction.class.php
class Default_HelloAction extends AgaviAction
{
public function execute(AgaviRequestDataHolder $rd)
{
// 1. 取得輸入 (GET/POST/COOKIE/FILES)
$name = $rd->getParameter('name', 'World');
// 2. 業務邏輯 (通常委派給 Model/Service)
$greeting = "Hello, {$name}! Welcome to Agavi.";
// 3. 設定輸出資料給 View
$this->setAttribute('greeting', $greeting);
$this->setAttribute('currentTime', date('Y-m-d H:i:s'));
return 'Success'; // 對應 HelloSuccessView
}
// 可選:輸入驗證
public function validate(AgaviValidator $validator)
{
$validator->addRule('name', new AgaviStringValidator(['max_length' => 50]));
}
}
<?php
// app/modules/Default/views/HelloSuccessView.class.php
class Default_HelloSuccessView extends AgaviHtmlView
{
public function setupHtml()
{
// 設定母版頁 (預設 app/templates/Master.php)
$this->setLayout('Master');
}
}
<?php // app/modules/Default/templates/HelloSuccess.php ?>
<h1><?= $t->get('greeting') ?></h1>
<p>Current time: <?= $t->get('currentTime') ?></p>
<p><a href="<?= $ro->gen('default.index') ?>">Back to Home</a></p>
<?xml version="1.0" encoding="UTF-8"?>
<ae:configurations xmlns:ae="https://agavi.org/agavi/config/global/envelope/1.0"
xmlns="https://agavi.org/agavi/config/parts/routing/1.0">
<ae:configuration>
<routes>
<route name="default.index" pattern="^/$" module="Default" action="Index" />
<route name="default.hello" pattern="^/hello(?:/(?P[^/]+))?$" module="Default" action="Hello" />
</routes>
</ae:configuration>
</ae:configurations>
# 內建開發伺服器 (需 PHP 5.4+)
cd myproject
php -S localhost:8000 -t pub
# 訪問 https://localhost:8000/hello/Agavi
下一篇將介紹:**表單處理、輸入驗證器、資料庫整合 (Doctrine/Propel)、錯誤處理與自訂輸出類型 (JSON/XML/RSS)**。