Created
November 28, 2009 08:51
-
-
Save jara/244448 to your computer and use it in GitHub Desktop.
Zend Framework Form Factory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// application/forms/Factory.php | |
class Default_Form_Factory { | |
/** | |
* Acts as a registry for loaded forms | |
* @var array | |
*/ | |
private static $_forms = array(); | |
/** | |
* Instantiate a form based on class name and module | |
* | |
* Usage: | |
* Default_Form_User class: Default_Form_Factory::create('user'); | |
* Account_Form_User class: Default_Form_Factory::create('user', 'account'); | |
* | |
* @param string $form | |
* @param string $module | |
* @param mixed $options | |
* @return Zend_Form | |
*/ | |
public static function createForm($form, $module = 'Default', $options = null) { | |
$formClass = self::_formClassName($form, $module); | |
if (array_key_exists($formClass, self::$_forms)) { | |
return self::$_forms[$formClass]; | |
} | |
$formInstance = new $formClass($options); | |
if ($formInstance instanceof Zend_Form) { | |
self::$_forms[$formClass] = $formInstance; | |
return $formInstance; | |
} | |
return new Zend_Form(); | |
} | |
/** | |
* Set a custom form instance based on class name and module | |
* | |
* Usage: | |
* Default_Form_User class: Default_Form_Factory::setForm($form, 'user'); | |
* Account_Form_User class: Default_Form_Factory::setForm($form, 'user', 'account'); | |
* | |
* @param Zend_Form $instance | |
* @param string $form | |
* @param string $module | |
*/ | |
public static function setForm($instance, $form, $module = 'Default') { | |
$formClass = self::_formClassName($form, $module); | |
self::$_forms[$formClass] = $instance; | |
} | |
/** | |
* Clear all loaded forms | |
*/ | |
public static function reset() { | |
self::$_forms[$formClass] = array(); | |
} | |
/** | |
* Build the form class name from the form name and module | |
* | |
* @param string $form | |
* @param string $module | |
* @return string | |
*/ | |
private static function _formClassName($form, $module) { | |
return ucfirst($module) . '_Form_' . ucfirst($form); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment