吉姆莱/formhandler

dev-master 2015-04-30 06:58 UTC

This package is not auto-updated.

Last update: 2024-09-28 18:10:30 UTC


README

与composer一起使用

composer require jimlei/formhandler:dev-master

创建将被表单(请求)修改的对象/实体

<?php // src/Entity/Article.php

namespace Acme\Entity;

class Article
{
    private $id;
    private $title;

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        $this->title = $title;
        return $this;
    }
}

创建将映射/验证请求中数据的表单

<?php // src/Form/ArticleForm.php

namespace Acme\Form;

use Acme\Entity\Article;
use Jimlei\FormHandler\Form;

class ArticleForm extends Form
{
    public function __construct(Article $article)
    {
        $fields = array(
            'title' => array(
                'type' => 'string',
                'maxLength' => '60',
                'required' => true
            )
        );

        parent::__construct($article, $fields);
    }
}

它依赖于Request->getData方法,因此你应该在你的请求数据处理(方法、数据、查询等)中实现RequestInterface。

<?php // src/Net/Request.php

namespace Acme\Net;

use Jimlei\FormHandler\RequestInterface;

/**
 * Maps a request to usable data.
 */
class Request implements RequestInterface
{
    private $data;

    public function __construct()
    {
        $this->data = json_decode(file_get_contents('php://input')) ?: array();
    }
    
    public function getData()
    {
        return $this->data;
    }
}

整合起来

<?php // index.php

use Acme\Entity\Article;
use Acme\Form\ArticleForm;
use Acme\Net\Request;

require 'vendor/autoload.php';

$request = new Request();
$article = new Article();

$form = new ArticleForm($article);
$form->handleRequest($request);

if ($form->isValid())
{
    // save article...
}

// do something with the errors
foreach ($form->getErrors() as $error)
{
  // log, add to flash message, display otherwise, etc.
}

你可以通过curl请求来测试它。尝试传递参数、更改表单字段类型/要求/长度等,并查看验证和错误的变化。

curl --data '{"title":"foo"}' localhost

可用类型

  • bool
  • date
  • datetime
  • email
  • float
  • int
  • ip
  • string
  • time
  • timestamp
  • url

可用验证

  • required (bool)
  • min (int)
  • max (int)
  • minLength (int)
  • maxLength (int)

运行测试

$ vendor/bin/phpunit