萬盛學電腦網

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

PHP 陣列驅動動態表單生成器:資料結構定義 UI 的靈活應用模式

概念:宣告式表單定義

將表單欄位屬性 (型別、驗證、樣式、提示) 定義為結構化陣列,由單一渲染函式/類別自動生成 HTML。優點:

  • 資料與視圖分離,易維護、易擴充
  • 後端驗證規則與前端屬性同源
  • 支援動態表單 (權限控制、A/B 測試、多語系)
  • 減少重複 HTML 代碼

核心資料結構設計

<?php
/**
 * 表單欄位定義陣列結構
 */
$formSchema = [
    'username' => [
        'type'        => 'text',
        'label'       => '帳號',
        'required'    => true,
        'attributes'  => [
            'placeholder' => '請輸入 4-16 位英數',
            'pattern'     => '^[a-zA-Z0-9]{4,16}$',
            'autocomplete' => 'username',
            'class'       => 'form-control',
        ],
        'validation'  => ['required', 'alpha_num', 'min:4', 'max:16'],
        'messages'    => [
            'required' => '帳號不可為空',
            'min'      => '帳號至少 4 字元',
        ],
    ],
    'email' => [
        'type'       => 'email',
        'label'      => '電子郵件',
        'required'   => true,
        'attributes' => [
            'placeholder' => 'example@domain.com',
            'class'       => 'form-control',
        ],
        'validation' => ['required', 'email'],
    ],
    'password' => [
        'type'       => 'password',
        'label'      => '密碼',
        'required'   => true,
        'attributes' => [
            'placeholder' => '至少 8 字元,含大小寫數字',
            'class'       => 'form-control',
        ],
        'validation' => ['required', 'min:8', 'regex:/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/'],
    ],
    'role' => [
        'type'       => 'select',
        'label'      => '角色',
        'required'   => true,
        'options'    => [
            'admin' => '管理員',
            'editor' => '編輯',
            'viewer' => '檢視者',
        ],
        'attributes' => ['class' => 'form-select'],
    ],
    'bio' => [
        'type'       => 'textarea',
        'label'      => '自我介紹',
        'required'   => false,
        'attributes' => [
            'rows' => 4,
            'class' => 'form-control',
        ],
    ],
    'agree_terms' => [
        'type'       => 'checkbox',
        'label'      => '我同意服務條款',
        'required'   => true,
        'attributes' => ['class' => 'form-check-input'],
    ],
    'submit' => [
        'type'       => 'submit',
        'label'      => '註冊',
        'attributes' => ['class' => 'btn btn-primary', 'value' => '註冊'],
    ],
];

通用渲染器實作

<?php
class FormRenderer
{
    public function render(array $schema, array $values = [], array $errors = []): string
    {
        $html = '<form method="post" novalidate>' . "\n";

        foreach ($schema as $name => $field) {
            $html .= $this->renderField($name, $field, $values[$name] ?? null, $errors[$name] ?? null);
        }

        $html .= '</form>';
        return $html;
    }

    private function renderField(string $name, array $field, $value, ?string $error): string
    {
        $type = $field['type'] ?? 'text';
        $label = $field['label'] ?? ucfirst($name);
        $required = !empty($field['required']);
        $attrs = $field['attributes'] ?? [];
        $attrs['name'] = $name;
        $attrs['id'] = $attrs['id'] ?? $name;

        // 合併 class
        $class = trim(($attrs['class'] ?? '') . ($error ? ' is-invalid' : '') . ($required ? ' required' : ''));
        $attrs['class'] = $class;

        // 必填屬性
        if ($required) $attrs['required'] = 'required';

        // 設定 value (除檔案/提交/重設/按鈕外)
        if (!in_array($type, ['file', 'submit', 'reset', 'button', 'checkbox', 'radio'], true)) {
            $attrs['value'] = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
        }

        // 建立屬性字串
        $attrStr = '';
        foreach ($attrs as $k => $v) {
            if ($v === true) $attrStr .= " $k";
            elseif ($v !== false && $v !== null) $attrStr .= " $k=\"" . htmlspecialchars((string)$v, ENT_QUOTES) . '"';
        }

        $html = '<div class="mb-3">';

        // Label (checkbox/radio 特殊處理)
        if (in_array($type, ['checkbox', 'radio'], true)) {
            $html .= '<div class="form-check">';
            $html .= "<input type=\"$type\"$attrStr>";
            $html .= "<label class=\"form-check-label\" for=\"{$attrs['id']}\">$label</label>";
            $html .= '</div>';
        } else {
            $html .= "<label for=\"{$attrs['id']}\" class=\"form-label\">$label";
            if ($required) $html .= ' <span class="text-danger">*</span>';
            $html .= "</label>";

            switch ($type) {
                case 'select':
                    $html .= "<select$attrStr>";
                    foreach (($field['options'] ?? []) as $val => $txt) {
                        $sel = ((string)$value === (string)$val) ? ' selected' : '';
                        $html .= "<option value=\"" . htmlspecialchars((string)$val) . "\"$sel>" . htmlspecialchars($txt) . "</option>";
                    }
                    $html .= '</select>';
                    break;
                case 'textarea':
                    $html .= "<textarea$attrStr>" . htmlspecialchars((string)$value) . '</textarea>';
                    break;
                default: // text, email, password, number, date, hidden...
                    $html .= "<input type=\"$type\"$attrStr>";
            }
        }

        // 錯誤訊息
        if ($error) {
            $html .= '<div class="invalid-feedback">' . htmlspecialchars($error) . '</div>';
        }

        // 說明文字
        if (!empty($field['help'])) {
            $html .= '<div class="form-text">' . htmlspecialchars($field['help']) . '</div>';
        }

        $html .= '</div>' . "\n";
        return $html;
    }
}

控制器整合範例

<?php
// RegisterController.php
class RegisterController
{
    public function show(): string
    {
        $schema = $this->getFormSchema();
        $renderer = new FormRenderer();
        return $renderer->render($schema);
    }

    public function store(): void
    {
        $schema = $this->getFormSchema();
        $input = $_POST;
        $errors = $this->validate($input, $schema);

        if ($errors) {
            $renderer = new FormRenderer();
            echo $renderer->render($schema, $input, $errors);
            return;
        }

        // 通過驗證,處理註冊邏輯...
        // $user = User::create($input);
        // 重導向防止重複提交
        header('Location: /login');
        exit;
    }

    private function validate(array $input, array $schema): array
    {
        $errors = [];
        foreach ($schema as $name => $field) {
            $value = $input[$name] ?? null;
            $rules = $field['validation'] ?? [];

            foreach ($rules as $rule) {
                $msg = $field['messages'][$rule] ?? "$name: $rule validation failed";

                // 簡易規則引擎示範
                if ($rule === 'required' && empty($value)) {
                    $errors[$name] = $msg;
                    break;
                }
                if (str_starts_with($rule, 'min:') && mb_strlen((string)$value) < (int)substr($rule, 4)) {
                    $errors[$name] = $msg;
                    break;
                }
                if (str_starts_with($rule, 'max:') && mb_strlen((string)$value) > (int)substr($rule, 4)) {
                    $errors[$name] = $msg;
                    break;
                }
                if ($rule === 'email' && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
                    $errors[$name] = $msg;
                    break;
                }
                if ($rule === 'alpha_num' && !ctype_alnum($value)) {
                    $errors[$name] = $msg;
                    break;
                }
                if (str_starts_with($rule, 'regex:') && !preg_match('/' . substr($rule, 6) . '/', $value)) {
                    $errors[$name] = $msg;
                    break;
                }
            }
        }
        return $errors;
    }

    private function getFormSchema(): array
    {
        // 回傳上方 $formSchema 定義
        return require __DIR__ . '/../schemas/register_form.php';
    }
}

進階擴充方向

  • 前端框架整合:輸出 JSON Schema,Vue/React 使用 @json-schema-form、react-jsonschema-form 直接渲染
  • 條件顯示:欄位加 `visible_when` 規則,根據其他欄位值動態顯示/隱藏
  • 巢狀欄位/陣列欄位:支援 `type: 'fieldset'` 包含子欄位、`type: 'repeater'` 動態增減項目
  • 檔案上傳預覽、拖曳上傳:前端元件化處理,後端只驗證結果
  • 整合驗證庫:Respect/Validation、Laravel Validator、Symfony Validator 替換簡易規則引擎

結語

陣列驅動表單生成器體現「配置勝過代碼」哲學。從簡單渲染器起步,漸進擴充驗證、條件邏輯、前端整合,能大幅減少重複表單代碼,提升開發效率與一致性。

copyright © 萬盛學電腦網 all rights reserved