monomelodies/公式

该软件包已被废弃,不再维护。作者建议使用monolyth/formulaic软件包。

面向对象的PHP5表单工具

1.5.11 2016-06-10 17:01 UTC

README

PHP5.4+的面向对象表单工具

此项目已停止开发

请参阅其后续项目:monolyth/formulaic

HTML表单很糟糕。好吧,不,它们非常方便,但编写和服务器端验证它们可能很痛苦。Formulaic提供了一套工具来简化这个过程。

基本用法

定义包含一些字段和其他要求的表单

<?php

use Formulaic\Get;
use Formulaic\Search;
use Formulaic\Button\Submit;

class MyForm extends Get
{
    public function __construct()
    {
        $this[] = (new Search('q'))->isRequired();
        $this[] = new Submit('Go!', 'submit');
    }
}

在您的模板中,您可以使用API手动调整输出,或者简单地对表单使用__toString以使用默认设置

<?php

$form = new MyForm;
echo $form;

您可以对单个字段使用__toString

<?php

$form = new MyForm;

?>
<form name="search" method="get">
    <!-- These two yield identical output using MyForm above: -->
    <?=$form[0]?>
    <?=$form['q']?>
</form>

以验证您的表单

<?php

$form = new MyForm;
if ($form->valid()) {
    // ...Perform the search...
}

获取错误列表

<?php

$form = new MyForm;
if ($errors = $form->errors()) {
    // ...Do error handling, or give feedback...
}

表单可以包含字段集

<?php

use Formulaic\Get;
use Formulaic\Fieldset;
use Formulaic\Search;
use Formulaic\Button\Submit;

class MyForm extends Get
{
    public function __construct()
    {
        $this[] = new Fieldset('Global search', function($fieldset) {
            $fieldset[] = new Search('q');
        });
        $this[] = new Fieldset('Search by ID', function($fieldset) {
            $fieldset[] = new Search('id');
        });
        $this[] = new Submit('Go!');
    }
}

在输出中

<form method="get">
    <?=$form['Global search']?>
    <?=$form['Search by ID']?>
    <?=$form['submit']?>
</form>

有关所有其他选项的完整文档请参阅完整文档