在对象上下文中将字符串转换为有效的PHP代码?

时间:2013-12-06 16:35:25

标签: php silex formbuilder

我在我的应用程序中使用Silex FormBuilder。构建器的结构如下:

$form = $app['form.factory']->createBuilder('form')
->add('name', 'text', array(
        'constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5)))
))
->add('email', 'text', array(
    'constraints' => new Assert\Email()
))
->add('gender', 'choice', array(
    'choices' => array(1 => 'male', 2 => 'female'),
    'expanded' => true,
    'constraints' => new Assert\Choice(array(1, 2)),
))
->getForm();

假设我将从块构建这样的构建器,这些块将作为整体存储在数据库中。总是,我会创建的任何形式,我知道,电子邮件字段将始终定义相同。所以我会从数据库中获取定义并预先创建表单。

->add('email', 'text', array(
'constraints' => new Assert\Email()))

当我从数据库(在我的情况下为posgresql)中获取此信息时,这将是一个字符串(因为数据库字段是文本类型)。
我的问题:是否有可能将其转换为有效代码?

我想到了这样的事情:

$form = $app['form.factory']->createBuilder('form')
foreach ($definitions as $definition) {
  something to do with the $definition;
}
->getForm();

但是,而不是foreach,createBuilder期望 - > add ...方法,这就是我陷入困境的地方。

最诚挚的问候,
卡米尔

1 个答案:

答案 0 :(得分:0)

/*Concidering $definitions = array("$form->add('email', 'text', array(
        'constraints' => new Assert\Email()
    ));"); 
*/
$form = $app['form.factory']->createBuilder('form');
foreach($definitions as $definition){
    eval($definition);
}
$form->getForm();

我不建议您像这样使用eval ...您最好存储参数以传递给函数以使其工作...您还可以创建一个函数或类来处理典型元素,例如您的电子邮件,所以你只需要引用数据库中的输入类型,有点像:

function addFormElement(&$form,$type){
    switch($type){
        case 'email':$form->add('email', 'text', array(
                    'constraints' => new Assert\Email()
                ));
        break;
    }
}
/*Concidering $definitions = array("email"); 
*/
$form = $app['form.factory']->createBuilder('form');
foreach($definitions as $definition){
    addFormElement($form,$definition);
}
$form->getForm();
相关问题