在早期的 PHP 開發中,手寫 HTML 表單不僅繁瑣,還難以維護一致的樣式與結構。本文介紹一個經典的 Form 類,它通過面向對象方式封裝表單元素生成邏輯,支持表格佈局與流式佈局雙模式,極大提升了開發效率。雖然現代框架已內置表單構建器,但理解其核心設計思想對掌握 PHP OOP 精髓極有幫助。
Form 類採用「構建器模式」思想:
$action、$method、$layout (表格/流式) 等全局屬性。form_text()、form_passwd()、form_select() 等對應各類 input 元素。form_item() 根據 $layout 決定輸出 <tr><th><td> 還是簡單的 <label><input>。CreateForm() 批量渲染元素數組。<?php
class Form {
public $layout = true; // 默認表格佈局
public $action, $method, $enctype, $name, $id, $class;
public function __construct($action, $method = "POST") {
$this->action = $action;
$this->method = $method;
}
public function form_start() {
$html = "<form action=\"{$this->action}\" method=\"{$this->method}\"";
foreach (['class', 'enctype', 'id', 'name'] as $attr) {
if ($this->$attr) $html .= " $attr=\"{$this->$attr}\"";
}
$html .= ">\n";
if ($this->layout) $html .= "<table>\n";
return $html;
}
// ...
}
?>
<?php
public function form_text($name, $id, $label_name, $label_for, $value = "") {
$input = "<input type=\"text\" name=\"{$name}\" id=\"{$id}\"";
if (isset($value)) $input .= " value=\"{$value}\"";
$input .= " />\n";
$label = $this->form_label($label_name, $label_for);
return $this->form_item($label, $input);
}
private function form_label($text, $for) {
return $for ? "<label for=\"{$for}\">{$text}:</label>" : "{$text}:";
}
private function form_item($label, $input) {
if ($this->layout) {
return "<tr>\n<th class=\"label\">{$label}</th>\n<td>{$input}</td>\n</tr>\n";
}
return $label . $input . "<br>\n";
}
?>
<?php
require_once("Form.php");
$form = new Form($_SERVER['PHP_SELF']);
$form->layout = false; // 切換為流式佈局
$username = $form->form_text("userid", "userid", "用戶名", "userid");
$password = $form->form_passwd("passwd", "passwd", "密碼", "passwd");
$submit = $form->form_button("", "submit", "submit", "登錄");
$form->CreateForm([$username, $password, $submit]);
?>
若在現代項目中復用此思路,建議:
require_once。FormElementInterface),便於擴展自定義組件(如日期選擇器、富文本編輯器)。form_start() 自動注入 <input type="hidden" name="_token">。這個 Form 類雖屬「上古」代碼,但其「配置驅動生成、佈局策略分離、統一入口渲染」的設計模式至今不過時。理解它,有助於你更深入地掌握現代框架(Laravel Form Builder、Symfony Form Component)的底層邏輯。