我正在学习使用Symfony2,根据我所读的文档,所有与Symfony表单一起使用的实体都具有空构造函数或者没有构造函数。(示例)
请参见:http://symfony.com/doc/current/book/index.html 第12章
http://symfony.com/doc/current/cookbook/doctrine/registration_form.html 我使用参数化构造函数来在创建对象时要求某些信息。Symfony的方法似乎是将强制执行留给验证过程,基本上依赖元数据断言和数据库约束来确保对象正确初始化,放弃了构造函数约束以确保状态。
考虑以下内容:
我不应该使用构造函数参数来做这件事吗?谢谢。
编辑:下面有答案。
请参见:http://symfony.com/doc/current/book/index.html 第12章
http://symfony.com/doc/current/cookbook/doctrine/registration_form.html 我使用参数化构造函数来在创建对象时要求某些信息。Symfony的方法似乎是将强制执行留给验证过程,基本上依赖元数据断言和数据库约束来确保对象正确初始化,放弃了构造函数约束以确保状态。
考虑以下内容:
Class Employee {
private $id;
private $first;
private $last;
public function __construct($first, $last)
{ .... }
}
...
class DefaultController extends Controller
{
public function newAction(Request $request)
{
$employee = new Employee(); // Obviously not going to work, KABOOM!
$form = $this->createFormBuilder($employee)
->add('last', 'text')
->add('first', 'text')
->add('save', 'submit')
->getForm();
return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
}
我不应该使用构造函数参数来做这件事吗?谢谢。
编辑:下面有答案。