草庐IT

php - Zend 框架 : Setting decorators and labels - should this be done in the view or the form class?

coder 2024-04-19 原文

我注意到许多(大多数?)人在使用 Zend Framework 时会在 Form 类本身中添加装饰器和标签。

class User_Form_Add extends Zend_Form
{
    public function init()
    {
        parent::init();
        $username = new Zend_Form_Element_Text('username');
        $username->setLabel('Username:')
                 ->setRequired(true)
                 ->addFilter('StringTrim')
                 ->addValidator('StringLength', $breakChainOnFailure = false, $options = array(1, 30))
                 ->setDecorators(array(
                     'ViewHelper',
                     array('Description', array('tag' => 'p', 'class' => 'description')),
                     array('Label',       array('requiredPrefix'      => '<span class="asterisk">*</span>&nbsp;', 'escape' => false)),
                     array('HtmlTag',     array('tag' => 'p', 'class' => 'element'))
                 ));
    }
}

但这肯定不是好的做法?我原以为装饰器和标签是 MVC 应用程序中 View 层的一部分。当我查看这个表单类时,它看起来被各种标记、标签和文本“污染”了,这些标记和文本本应位于 View 层。

这种方法意味着如果您需要修改表单的标记,则需要同时使用表单类 View 脚本。

我不喜欢这个概念,因此在呈现表单时将表单和装饰器分离到实际的 View 脚本中。我想将我的应用程序的这些相互冲突的“关注点”分开。

class User_Form_Add extends Zend_Form
{
    public function init()
    {
        parent::init();
        $username = new Zend_Form_Element_Text('username');
        $username->setRequired(true)
                 ->addFilter('StringTrim')
                 ->addValidator('StringLength', $breakChainOnFailure = false, $options = array(1, 30));
    }
}

//添加.phtml:

$this->form->username->setLabel('Username:');
$this->form->username->setDecorators(array(
    'ViewHelper',
    array('Description', array('tag' => 'p', 'class' => 'description')),
    array('Label',       array('requiredPrefix'      => '<span class="asterisk">*</span>&nbsp;', 'escape' => false)),
    array('HtmlTag',     array('tag' => 'p', 'class' => 'element'))
));

echo $this->form->render();

这使表单类变得干净,并且非常类似于模型类——这就是我对表单类的看法;它包含过滤器、验证器等,它们都与业务逻辑相关。

如果您随后采用这种方法,则可以更轻松地将您的表单与您的模型集成,这样您就可以直接从您的模型中重用/访问表单验证器和过滤器 - 无需创建装饰器等不必要的开销.

http://weierophinney.net/matthew/archives/200-Using-Zend_Form-in-Your-Models.html

至于保持你的 View 脚本干燥,这样你就不会在多个 View 中重复相同的标签和装饰器(即当你需要多次呈现相同的表单,但在不同的 View 脚本中),我发现你可以使用 ViewScript 装饰器将表单的可重用部分分离出来,以保持干燥。

编辑:同样,我们也可以用适合我们项目的装饰器覆盖默认装饰器,以避免一开始就不必要地声明装饰器。

所以我的实际问题是:

为什么没有其他人像这样使用他们的表单?您认为这种方法有什么缺点?

如果可以在 View 层中轻松添加装饰器和表单标签,为什么还要在表单类中创建它们?

我不明白为什么我看到的几乎所有 Zend_Form 用法都包括在表单类本身中添加装饰器/标签。

最佳答案

Why isn't anyone else working with their forms like this?

没想到。非常好的方法。

关于php - Zend 框架 : Setting decorators and labels - should this be done in the view or the form class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4190238/

有关php - Zend 框架 : Setting decorators and labels - should this be done in the view or the form class?的更多相关文章

随机推荐