萬盛學電腦網

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

Zend Framework 1 表單建立完整教學:從自動載入到視圖渲染

Zend Framework 1 的 `Zend_Form` 元件提供強大的表單建構、驗證、過濾與裝飾功能。本文以「留言板表單」為例,完整示範從自動載入配置、表單類別建立、控制器處理到視圖渲染的標準流程。

步驟 1:配置自動載入與 include_path

<?php
// public/index.php 或 Bootstrap.php
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
$loader->registerNamespace('Application_');           // 應用命名空間
$loader->registerNamespace(['Foo_', 'Bar_']);         // 第三方庫命名空間

// 關鍵:確保 forms 目錄在 include_path 中
set_include_path(implode(PATH_SEPARATOR, [
    realpath(APPLICATION_PATH . '/../library'),
    realpath(APPLICATION_PATH . '/forms/'),   // ← 表單類別目錄
    get_include_path(),
]));

步驟 2:建立表單類別

路徑:application/forms/Guestbook.php

<?php
class Application_Form_Guestbook extends Zend_Form
{
    public function init()
    {
        $this->setMethod('post');

        // Email 欄位
        $this->addElement('text', 'email', [
            'label'      => '您的 Email:',
            'required'   => true,
            'filters'    => ['StringTrim'],
            'validators' => [
                ['EmailAddress', true],
            ],
        ]);

        // 留言內容
        $this->addElement('textarea', 'comment', [
            'label'      => '留言內容:',
            'required'   => true,
            'validators' => [
                ['StringLength', false, [0, 2000]],
            ],
        ]);

        // 驗證碼
        $this->addElement('captcha', 'captcha', [
            'label'    => '請輸入下方 5 位字元:',
            'required' => true,
            'captcha'  => [
                'captcha' => 'Figlet',
                'wordLen' => 5,
                'timeout' => 300,
            ],
        ]);

        // 送出按鈕
        $this->addElement('submit', 'submit', [
            'ignore' => true,
            'label'  => '送出留言',
        ]);

        // CSRF 保護
        $this->addElement('hash', 'csrf', ['ignore' => true]);
    }
}

步驟 3:控制器處理表單

路徑:application/controllers/GuestbookController.php

<?php
class GuestbookController extends Zend_Controller_Action
{
    public function signAction()
    {
        $request = $this->getRequest();
        $form    = new Application_Form_Guestbook();

        if ($request->isPost()) {
            if ($form->isValid($request->getPost())) {
                // 驗證通過,取得過濾後資料
                $data = $form->getValues();

                // 儲存邏輯(示意)
                $comment = new Application_Model_Guestbook($data);
                $mapper  = new Application_Model_GuestbookMapper();
                $mapper->save($comment);

                // PRG 模式重導向
                return $this->_helper->redirector('index');
            }
            // 驗證失敗:$form 內含錯誤訊息,直接渲染視圖
        }

        // 指派表單給視圖
        $this->view->form = $form;
    }
}

步驟 4:視圖渲染表單

路徑:application/views/scripts/guestbook/sign.phtml

<h1>留言板</h1>
<?php
$this->form->setAction($this->url()); // 設定提交網址
echo $this->form;                     // 自動輸出完整表單 HTML
?>

進階客製化:裝飾器與佈局

預設輸出為 `

` 結構。若需自訂 HTML 結構(如 Bootstrap 類別),可自訂裝飾器:

<?php
// 在表單 init() 中
$this->setDecorators([
    'FormElements',
    ['HtmlTag', ['tag' => 'div', 'class' => 'form-container']],
    'Form',
]);

// 元素層級裝飾器
$this->setElementDecorators([
    'ViewHelper',
    'Errors',
    ['HtmlTag', ['tag' => 'div', 'class' => 'form-group']],
    ['Label', ['tag' => 'label', 'class' => 'control-label']],
]);

// 按鈕特殊處理
$submit = $this->getElement('submit');
$submit->setDecorators(['ViewHelper', ['HtmlTag', ['tag' => 'div', 'class' => 'form-group']]]);

常見問題排查

問題解決方案
Class 'Application_Form_Guestbook' not found確認 `forms/` 在 `include_path`,且檔名 `Guestbook.php`、類別名 `Application_Form_Guestbook` 符合 PSR-0
驗證碼不顯示確認 GD + FreeType 已啟用;`Figlet` 需安裝 `php-pear/Text_CAPTCHA` 套件
CSRF 驗證失敗確認 Session 已啟動(`Zend_Session::start()`),且表單包含 `hash` 元素

最佳實踐總結

  1. 表單類別置於 `application/forms/`,命名空間 `Application_Form_*`。
  2. 驗證邏輯封裝在表單類別內(`init()`),控制器僅負責流程控制。
  3. 使用 `isValid()` 觸發驗證,`getValues()` 取得已過濾資料。
  4. 視圖僅負責渲染,使用 `$this->form` 輸出或逐元素渲染(`$this->form->email->renderLabel()` 等)。
  5. 生產環境啟用類別映射快取,避免每請求掃描檔案系統。

遵循此標準流程,能建立結構清晰、可測試、易維護的 ZF1 表單系統。

copyright © 萬盛學電腦網 all rights reserved