灵活的表单构建器,具有数据验证和预处理功能
v1.0.0
2018-01-29 20:36 UTC
Requires
- php: >=7.0
- nesbot/carbon: ~1.22
- psr/http-message: ~1.0
- vlucas/valitron: ~1.4
Requires (Dev)
- friendsofphp/php-cs-fixer: ~2.10
- phpunit/phpunit: ~6.0
This package is auto-updated.
Last update: 2024-08-29 04:31:35 UTC
README
灵活的表单构建器,具有数据验证和预处理功能。
安装
从命令行运行 Composer
composer require misantron/bricks
或在 composer.json
中添加依赖项
{
"require": {
"misantron/bricks": "dev-master"
}
}
用法
通过继承 \Bricks\AbstractForm
创建新表单。必须实现 fields()
抽象方法,使用配置数组
class SomeForm extends \Bricks\AbstractForm { protected funtion fields(): array { return [ 'foo' => [ 'type' => 'string', // using for data type cast 'validators' => [ 'required' => true, 'lengthMax' => 64, ], ], 'bar' => [ 'type' => 'integer', // using for data type cast 'validators' => [ 'required' => true, 'in' => function () { return [1, 2]; } ], 'cleanup' => true, // flag that field will be deleted from getData() method call response ], ]; } }
在应用程序控制器/服务等内部进行表单工作流程
$request = Request::fromGlobals(); // must implements \Psr\Http\Message\RequestInterface $default = [ 'foo' => 'test', ]; $form = \SomeForm::create() ->setData($default) // allows to pass an initial data before handling the request ->handleRequest($request) // get data from the request and data processing ->validate(); // data validation $data = $form->getData(); // extracting processed and validated data from form
内置字段类型
string
,integer
,float
,boolean
,array
(包含不同类型的元素),dateTime
(将日期时间字符串或时间戳转换为 Carbon 对象),intArray
,strArray
,floatArray
可以轻松添加自定义用户类型
class MyTransducer extends \Bricks\Data\Transducer { private funtion myType($value) { // your custom logic here } }
内置字段验证规则
请参阅 Valitron 文档。如果表单数据无效,将抛出 \Bricks\Exception\ValidationException
try { $form->validate(); } catch (\Bricks\Exception\ValidationException $e) { var_dump($e->getData()); // getting fields error data }