Zend Framework:如何为其他视图助手创建一个抽象视图助手来扩展?

时间:2010-09-22 00:12:27

标签: php zend-framework zend-form-element

我需要在Zend Framework应用程序中创建一些自定义表单元素(带有自定义视图助手)。问题是它们各自都很相似。我想创建一个基本视图助手类,每个类都可以扩展,并且我将需要一个抽象函数。

解决方案:

因此,如果我的Picker元素是抽象类,ContactPickerOrganizationPicker是扩展类...

表单元素:

class My_Form_Element_ContactPicker extends My_Form_Element_Picker
{
    /**
     * Default form view helper to use for rendering
     * @var string
     */
    public $helper = "contactPickerElement";
}

视图助手:

class My_View_Helper_ContactPickerElement extends My_View_Helper_PickerElement
{
    public function contactPickerElement($name, $value = null, $attribs = null)
    {
        // I don't need to do anything in this function.
        // I only need the parent to do all the work.
        return parent::pickerElement($name, $value, $attribs);
    }

    protected function myAbstractFunctionThatMustBeImplemented()
    {
        // This function will do all the work specific to this extending class.
        $model = new ContactModel();
        return $model->foobar;
    }
}

这是抽象视图助手:

abstract class Evanta_View_Helper_PickerElement extends Zend_View_Helper_FormElement
{
   /**
    * This function would have been called automatically, but since it's being extended...
    * Any extending classes must remember to manually call this function 
    */
   public function modalPickerElement($name, $value = null, $attribs = null)
    {
        $html = 'My picker element HTML';
        return $html;
    }

    /**
     * This function must be implemented by any extending classes
     */
    abstract protected function myAbstractFunctionThatMustBeImplemented();
}

1 个答案:

答案 0 :(得分:4)

在您Bootstrap的某个地方,您需要定义表单资源的去向,我建议使用自动加载器:

$autoloader->addResourceType('default_form', 'forms/', 'Form');

我加载自动加载器的整个方法如下所示

protected function _initAutoload()
{
    $autoloader = new Zend_Application_Module_Autoloader(array(
            'namespace' => 'Default_',
            'basePath'  => $this->_root,
        ));

    // Here a define a resource named 'default_form', this can be anything,
    // 2nd param is the path relative to my application folder,
    // and 3rd param is the prefix for the classes inside that folder
    $autoloader->addResourceType('default_form', 'forms/', 'Form');

    Zend_Loader_Autoloader::getInstance()->setFallbackAutoloader(true);

    return $autoloader;
}

然后,您可以在名为forms的{​​{1}}文件夹中创建一个文件夹,然后在名为Element的文件中创建一个文件夹并定义该类,您可以覆盖Default_Form_Element_Picker.php之类的函数,{ {1}},isValid()setValues()getValue()

loadDefaultDecorators()

您可以通过创建名称为__construct()Default_Form_Element_Picker extends Zend_Form_Element_Xhtml { }

的文件来扩展此类以制作其他表单元素
Default_Form_Element_ContactPicker.php

您也可以在此处添加用于创建表单的类,将其命名为Default_Form_Element_OrganizationPicker.php

Default_Form_Element_ContactPicker extends Default_Form_Element_Picker {

}

Default_Form_Element_OrganizationPicker extends Default_Form_Element_Picker {

}

文件结构

Default_Form_A.php