trt / formable
v0.1
2015-05-27 10:51 UTC
Requires
- symfony/form: ^2.3
- symfony/framework-bundle: ^2.3
- symfony/validator: ^2.3
Requires (Dev)
- phpspec/phpspec: ^2.2
- phpunit/phpunit: ^4.6
This package is not auto-updated.
Last update: 2022-02-01 12:47:55 UTC
README
Formable Symfony Bundle
为什么?
因为将数据从 Web 请求传输到域的最干净方式是使用 DTO。对于简单的 DTO,Symfony 强迫你创建 2 个类,即 FormType
类和 SomethingDTO
类。
如何?
此 Bundle 允许您通过 @Formable()
注解来描述 DTO。让我们看看一个例子。
例子
数据传输对象
use Formable\Definition\Formable; use Symfony\Component\Validator\Constraints as Assert; class PublishPostCommand { /** * @Formable(name="title", dataType="text") * * @Assert\Length(max=250) */ public $title; /** * @Formable(name="content", dataType="text") */ public $content; /** * @Formable(name="tags", dataType="collection", options={ * "type"="text", * "allow_add"=true * }) * * @Assert\Count( * min = "2" * ) * */ public $tags; /** * @Formable(name="date", dataType="date", options={ * "widget"="single_text", * "format"="yyyy-M-d" * }) */ public $date; }
嵌套 DTO
/** * @var * * @Formable(name="moneyDTO", class="Formable\Tests\Integration\DTOs\TestMoneyDTO") */ public $moneyDTO;
控制器
public function publishAction(Request $request) { $publishCommand = new PublishPostCommand(); $publishCommand->date = new \DateTime('now'); $form = $this->get('trt.formable')->generate($publishCommand); $form->submit($request->request->all(), false /* Do not clear missing data */); if ($form->isValid()) { ... } }
注解深入
@Formable()
注解遵循 Symfony\Component\Form\FormBuilderInterface
接口。
参数:
- name: [string] 字段名
- dataType: [string] 表单类型
- options: [array] 表单类型选项
/** * @Formable(name="date", dataType="date", options={ * "format"= IntlDateFormatter::MEDIUM, * "days" = {1,2,3,4} * }) */ public $date;
安装
composer require trt/formable
// Register the Bundle class AppKernel extends Kernel { public function registerBundles() { $bundles = array( ... new \Formable\Bundle\FormableBundle(), ); return $bundles; } }
运行测试
bin/test