Zend Framework 1(ZF1)提供強大的 Zend_Form 元件,支援表單元素定義、過濾、驗證、CSRF 保護等。本文以「留言板」為例,示範從環境設定、Form 類別建立、Controller 處理到 View 渲染的完整流程。
於 Bootstrap.php 或啟動檔案設定自動載入器:
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
$loader->registerNamespace('Application_'); // 專案命名空間
$loader->registerNamespace(array('Foo_', 'Bar_')); // 多重命名空間
// $loader->setFallbackAutoloader(true); // 不建議開啟,效能較差
確保 application/forms/ 目錄在 include_path 中:
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
realpath(APPLICATION_PATH . '/forms/'),
get_include_path(),
)));
Application_Form_Guestbook檔案位置:application/forms/Guestbook.php
class Application_Form_Guestbook extends Zend_Form
{
public function init()
{
$this->setMethod('post');
// Email 欄位
$this->addElement('text', 'email', array(
'label' => '您的 Email:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array('EmailAddress'),
));
// 留言內容
$this->addElement('textarea', 'comment', array(
'label' => '留言內容:',
'required' => true,
'validators' => array(
array('StringLength', false, array(0, 200))
),
));
// 驗證碼
$this->addElement('captcha', 'captcha', array(
'label' => '請輸入下方 5 位字元:',
'required'=> true,
'captcha' => array(
'captcha' => 'Figlet',
'wordLen' => 5,
'timeout' => 300,
),
));
// 送出按鈕
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => '送出留言',
));
// CSRF 保護
$this->addElement('hash', 'csrf', array('ignore' => true));
}
}
檔案:application/controllers/GuestbookController.php
class GuestbookController extends Zend_Controller_Action
{
public function signAction()
{
$form = new Application_Form_Guestbook();
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
// 儲存邏輯(此處略)
// $comment = new Application_Model_Guestbook($form->getValues());
// $mapper = new Application_Model_GuestbookMapper();
// $mapper->save($comment);
return $this->_helper->redirector('index');
}
}
$this->view->form = $form; // 將表單物件傳給 View
}
}
檔案:application/views/scripts/guestbook/sign.phtml
請使用下方表單簽名:
<?php
$this->form->setAction($this->url());
echo $this->form;
?>
Application_Form_Guestbook 對應 application/forms/Guestbook.php,自動載入器依 PSR-0 風格解析。isValid() 會自動執行所有元素的過濾器與驗證器。hash 與 captcha 元素可有效防禦跨站請求偽造與機器人灌水。