March 17, 2006

Using Zend Framework, Smarty, and QuickForm to Quickly Deploy PHP Applications

Posted at March 17, 2006 06:02 PM in PHP .

I began work this week on my first project utilizing the Zend Framework. The Zend Framework, although still alpha, provides some time-saving features for PHP web application developers. The largest time-saving feature for me so far has been the Zend Controller component, which is the building block for the MVC pattern. Basically, it allows you to create controllers and handlers to process requests. For example, /admin/index gets mapped to the 'index' action of the 'admin' controller. Inside the code, all you have to do is create classes to represent each controller and functions in those classes to process the handlers. Each handler function simply outputs the desired data to the browser. Easy as pie.

When working with the Zend Framework, I was reluctant to give up two tools that have served me well: Smarty, a PHP template engine, and PEAR's HTML QuickForm, a class that handles form generation and validation. Using Zend Framework's easily extensible design patterns, I settled on a design pattern that allows me to easily integrate all three of these components.

First, I created a Smarty template for displaying QuickForm-generated forms:

<table border="0">
  <form{$form.attributes}>{$form.hidden}
  
  {foreach item=sec key=i from=$form.sections}
    <tr>
      <td colspan="2" style="padding-bottom: 20px">
        <b>{$sec.header}</b>
      </td>
    </tr>
    
    {foreach item=element from=$sec.elements}
      {if $element.type eq "submit" or $element.type eq "reset"}
        {if not $form.frozen}
        <tr>
          <td> </td>
          <td align="left">{$element.html}</td>
        </tr>
        {/if}
      {else}
        <tr>
          <td align="right" valign="top">
            {if $element.required && $element.label}<font color="red">*</font>{/if}<b>{if $element.label}{$element.label}:{/if}</b></td>
          <td>
        {if $element.error}<font color="red">{$element.error}</font><br />{/if}
        {if $element.type eq "group"}
          {foreach key=gkey item=gitem from=$element.elements}
            {$gitem.label}
            {$gitem.html}{if $gitem.required}<font color="red">*</font>{/if}                           
            {if $element.separator}{cycle values=$element.separator}{/if}
          {/foreach}
        {else}
          {$element.html}
        {/if}
        <div style="font-size: 80%;">{$element.label_note}</div>
        </td>
      </tr>
      {/if}
    {/foreach}
  {/foreach}
  
  {if $form.requirednote and not $form.frozen}
  <tr>
    <td> </td>
    <td valign="top">{$form.requirednote}</td>
  </tr>
  {/if}
    
  </form>
  
</table>

I saved this file as genericForm.tpl.

Next, I extended the Zend Framework View class to integrate with Smarty:

<?php

Zend::loadClass('Zend_View_Abstract');

require_once 'Smarty/Smarty.class.php';

class My_View extends Zend_View_Abstract
{
private $_smarty;

public function __construct($config = array()) {
parent::__construct($config);

$this->_smarty = new Smarty();

$root = Zend::registry('config')->get('root', 'project');

$this->_smarty->template_dir = $root.'application/views/';
$this->_smarty->compile_dir = $root.'tmp/templates_c/';
$this->_smarty->config_dir = $root.'tmp/configs/';
$this->_smarty->cache_dir = $root.'tmp/cache/';

}

public function render($name) {
$file = $name.'.tpl';

$this->assign('basehref', Zend::registry('config')->get('htmlroot', 'project'));

return $this->_smarty->display($file);
}

public function assign($spec) {
$args = func_get_args();
call_user_func(array('parent', 'assign'), $args);

if (is_string($spec)) {
$arg = func_get_arg(1);
$this->_smarty->assign($spec, $arg);
} elseif (is_array($spec)) {
foreach ($spec as $k=>$v) {
$this->_smarty->assign($k, $v);
}
}
else {
throw new Zend_View_Exception('assign() expects a string or array');
}
}

public function renderForm(HTML_Quickform &$f) {
$renderer = new HTML_QuickForm_Renderer_Array(true, true);

$f->accept($renderer);

$this->assign('form', $renderer->toArray());

$this->render('genericForm');
}

}

?>

Finally, I build my controllers. Here is an example:

<?php

require_once 'Zend/Controller/Action.php';

class IndexController extends Zend_Controller_Action {
public function indexAction() {
$form = new HTML_QuickForm('My_Form', 'post', 'index');

$form->addElement('header', 'header', 'My Form Test');

$form->addElement('text', 'name', 'Your Name', array('size'=>30, 'maxlength'=>255));
$form->addRule('name', 'Your name is required');
$buttons[] = &HTML_QuickForm::createElement('submit', 'submit', 'Submit');
$buttons[] = &HTML_QuickForm::createElement('reset', 'clear', 'Reset');

$form->addGroup($buttons, null, null, ' ');

$view = Zend::registry('view');
$view->renderForm($form);
}

public function noRouteAction() {
echo 'No route to action';
}
}

?>

All that is left is verifying the form. To do this, after the $form object is completely built, call $form->validate(). If the return is true, you can do what you want with the form variables. I recommend using the $this->_forward call within the controller and dedicate another handler to processing the form submission. If the form does not validate, just call $view->renderForm($form) again.

Trackback

You can ping this entry by using http://blog.case.edu/gps10/mt-tb.cgi/6648 .

Comments

Hi! My name is Chris and I work at Help.com. One of our members posted a question and after reading your site I thought you might have the expertise give some guidance about an advice resource for this person. At issue:

"How does one find broken links and repair them in a php cart? My site is only partly working after I did a minor update. I have a 404 error when trying to navigate from one php document to another. I am totally ignorant about web sites. Any help would be appreciated. http://stubbytails.com trying to go from catalog to add to cart does not work?"

Posted by Chris at April 12, 2006 04:37 PM

Unsere gratis online casinos Downloads enthalten v?llig arbeitende Versionen der online casinos Software, damit Sie alle Eigenschaften des realen Produktes f?r 30 Tage erleben k?nnen. online casinos http://kasino-bonus.kde8.de [URL=http://kasino-bonus.kde8.de]online casinos[/URL]

Posted by online casinos - 1638243 at November 16, 2006 11:45 PM

Unsere gratis online casinos Downloads enthalten v?llig arbeitende Versionen der online casinos Software, damit Sie alle Eigenschaften des realen Produktes f?r 30 Tage erleben k?nnen. online casinos http://casino-zahlungsmethoden.kde8.de [URL=http://casino-zahlungsmethoden.kde8.de]online casinos[/URL]

Posted by online casinos - 1634432 at November 17, 2006 02:15 AM

Danke f?r Ihr Interesse an online casino. Bitte reichen Sie das Formal unten ein und ein Verkaufsrepr?sentant von online casino tritt mit Ihnen in Verbindung. online casino http://kasino-zahlungsmethoden.kde8.de [URL=http://kasino-zahlungsmethoden.kde8.de]online casino[/URL]

Posted by online casino - 1887331 at November 17, 2006 05:18 AM

casino is the world's leading diversified manufacturer of casino and control technologies systems. casino http://www.electric-products.net [URL=http://www.electric-products.net]casino[/URL]

Posted by casino - 1442199 at November 18, 2006 01:12 AM

wkhac jxqvkcun xvrkbm dyeiczsu moqnx xjzny exbcjaim

Posted by leqtyoun azhueob at November 19, 2006 06:16 AM

nyjg jwoydg xebovp xkceph kfezsg gxewsv eogcas usjvbmt klcnmx

Posted by lpwbym hatgbz at November 19, 2006 06:16 AM

If you?ve ever felt there was something holding you back in life, ruining your plans and stopping you from being who you want to be, you were right. We call it casino. casino http://www.traveling-guides.net/ [URL=http://www.traveling-guides.net/]casino[/URL]

Posted by casino - 1461791 at November 22, 2006 07:43 PM

In Oklahoma dogs must have a permit signed by the mayor in order to congregate in groups of three or more on private property cialis stories [URL=http://admin.albright.edu/spiritawards/inc/Ciales-And-Levetra.html] cialis stories[/URL] http://admin.albright.edu/spiritawards/inc/Ciales-And-Levetra.html

Posted by cialis stories at December 28, 2006 04:11 AM

In Oklahoma females are forbidden from doing their own hair without being licensed by the state morgage payoff [URL=http://ishi.arp.harvard.edu/atmobs/docs/Interest-Only-Mortgages.html] morgage payoff[/URL] http://ishi.arp.harvard.edu/atmobs/docs/Interest-Only-Mortgages.html

Posted by morgage payoff at January 4, 2007 02:09 PM

Post a comment










Remember personal info?