Generic Data save with Zend Framework

This technical article hilights one the famous ideal goal we all want to achieve : scaffolding, CRUD, BREAD, call it what you want, all we want is to get rid of repetitive sql query writing.  Zend framework provides powerful data abstraction  and here are a few tips to use Zend_DB_Table to its best. Of course this article assumes you have an idea of MVC development with Zend Framework.

Why are we doing this ? in the course of writing ajax actions, we needed our controller to react to any POST provided by specific forms : whatever the fields in the form, we want them to be saved to our table. Code below is a specific implementation of a controller that responds to specific ajax queries. Please bear in mind that it is only provided as an example of generic query action. Other protions of code are not optimal, such as viewless actions in the renderAjax method, not the best.

Controller Implementation

Our controller is a simple Zend_Controller_Action. We load the database model at init time, and specify the primary key  (node parameter) in a class variable. Note that our data model is also stored in a class variable.

  1.  
  2. class UserController extends Zend_Controller_Action
  3. {  
  4. public function init()
  5.     {
  6.         $this->session = new Zend_Session_Namespace(‘User’);
  7.       //  $this->view->translate = Zend_Registry::get(’Zend_Translate’);
  8.                 require_once ‘models/Users.php’;
  9.                 $this->data=new Users();
  10.                 $this->node = $this->getRequest()->getParam(node);
  11.                 WXC_Log::log("init node : " . $this->node);
  12.     }
  13.  

Quick look at the model

at this stage I specify on particular function I like to implement in Zend Framework Models : the primary key ! Other functions of the model could include add, delete and update : we’ll see below that our generic data admin prefers to do the job in the controller.

  1.  
  2. class Users extends Zend_Db_Table_Abstract  
  3. {
  4.     protected $_name = ‘users’;
  5.         public function primaryKey()
  6.         {
  7.                 $info = $this->info();
  8.                 return $info[primary][1];
  9.         }
  10. }
  11.  

Back to the crontroller : the renderAjax method is a quick one that stops the view from being rendered. If you are a specialist of Zend Framework you will notice that this can be better performed with the contextSwitch action helper. Use the code below only for testing, for production you’d rather spend a few minutes learning about helpers !

  1.  
  2.                 private function renderAjax()
  3. {
  4.                 $this->_helper->layout->disableLayout();
  5.                  $this->_helper->viewRenderer->setNoRender();
  6. }
  7.  

Action !

Listing records is the first thing you want to look for when working at data scaffolding. the code below reads metadata from the table, lists all columns from your table, fetches data and returns them as JSON (ready for extjs grid display, by the way).

  1.  
  2.  public function listAction()
  3. {       
  4.          $this->renderAjax();
  5.          
  6.           if (null === $select)    $select = $this->data->select();
  7.  
  8.       $thRowSet = $this->data->fetchAll( $this->data->select());
  9.  
  10.         $nodes=array();
  11.          $arrMeta=$this->data->info();
  12.                 $arrCols=$arrMeta[cols];
  13.  
  14. foreach($thRowSet as $row ){
  15.         $arr_node=array();
  16. foreach ($arrCols as  $v)
  17.         $arr_node[$v]=$row->$v;
  18.        
  19.         $nodes[]=$arr_node;
  20. }
  21.          
  22.         echo Zend_Json::encode( $nodes );
  23. }
  24.  

The next step would be to add records : we have not worked on this yet so you’ll want to try this with tables that have a few records in them. The method below works with two types of data sets.

  1. Multiple column form submit :this would be the classical response to a from submission, where each field bears the NAME of the database field, and obvisouly the value is the data. Such forms are transmitted via FORM array with key / value pairs. We read the POST (getRequest->getParam) that match metadata built from the database table column array. We then provide a clean arrData array of new data for the update() method of our Zend_Db_Table instanciation. This method takes two arguments: the first is the associative array mapping columns to change to new values to assign to these columns. The second is the where clause that we built from the primary key
  2. Single column submit : the technique is useful when working with extjs in place editing, where one piece of code can edit multiple fields. The field variable contains the database column name and the value is the data. We add a check that matches the field against database table column names
  1.  
  2. public function saveAction()
  3. {
  4.         $this->renderAjax();
  5. $id= $this->node;
  6.  $key = $this->data->primaryKey();
  7. $strWhere = $key. ‘=’  . $id;
  8.  
  9.  $arrMeta=$this->data->info();
  10.  
  11. // all columns submit
  12. $arrCols=$arrMeta[cols];
  13. $arrData=array();
  14. reset($arrCols);
  15. while (list($k,$v)=each($arrCols))
  16.         {
  17.                  if ($v!="parent_id"  && $v!= $this->data->primaryKey()
  18.                   && array_key_exists($v, $this->getRequest()->getParams()))
  19.                  {
  20.                         $arrData[$v]=$this->getRequest()->getParam($v);
  21.                        
  22.                         }
  23.         }
  24.        
  25. //single column submit via field/ value 
  26. if ($this->getRequest()->getParam(‘field’)!="")
  27. {$field = $this->getRequest()->getParam(‘field’);
  28. $value= $this->getRequest()->getParam(‘value’);
  29. $arrData[$field] =$value;
  30.  
  31. }
  32.  
  33.  
  34.   if (is_array($arrData))
  35.         {                
  36.           try{      $this->data->update($arrData,$strWhere);
  37.          echo 1;}
  38.           catch(Zend_Exception $e){  echo 0;}
  39.  
  40.        
  41.          
  42.         }
  43. else echo 0;
  44.  
  45. }
  46.  

A good start for extjs development : Hope this is useful for you !!

Monday’s web applications

Javascript libraries

While EXTJS 3.0 is on the way with a roadmap setting deadlines for early 2009, Jquery continues its path on the way to serious lightweight alternative to the massive EXT : JX extension for Jquery includes the viewport paradigm on which relies every EXT JS application.

Web based interfaces

In spite of huge progress and impressive use of ease, Jquery is not there yet : for the development of applications many developers have chosen the exhaustivity of EXT JS. Have a look at google code hosted project in development : ecartcommerce, CMS jimw, both ext js and zend framework based. In the world of content management systems, mysource is making the news with a new video that demonstrates inline editing, and other exciting Rich Application features.

Zend Framework extensions

Zend framework might not be as popular as other famous programming frameworks such as CAKE PHP or symfony. But still it’s getting quite usable with version 1.7 approaching and a growing number of serious of libraries are hitting the ground. We’ve already covered code generation,  scaffolding and RAD with Zend framework in   previous articles, this article covers lower  level libraries from Zym Projet

Zym Project includes a powerful navigation abstraction that can help building pages hierachy in a CMS application for example. Other goodies include the bootstrap class, that takes all configuration from ini files (bootstrap class also exists in another ZF extension, ZENDEX). Some classes of Zym Project have been integrated into 1.6 official release of Zend Framework. API classes Reference guide is available online.

Zend Framework hierarchical Zend_Db_Table extension

After a few hours looking for a good implementation of recursive data with Zend Framework, I came across Hector Virgen’s table abstraction for nested recursive tables, which uses the efficiency of the Modified Preorder Tree Traversal method that retrieves descendents and ancestors faster that with the old parent_id reference. In fact parent_id is not needed any more but in the example below we will keep the parent_id implementation. My aim here is to implement a draggable tree with data from this Zend_DB_Table abstraction. Setting up ext js with Zend Framework is not that hard, especially when many tutorials have been posted around for extjs tree with other frameworks such as Cake PHP .
Read the rest of this entry »

Omeka : exhibit engine

what is nice about Omeka CMS is not the backend : you will find in the admin sandbox that most sections of the restricted area, while perfectly efficient, lack today’s common AJAX reactivity.  But on the front end, the result is stunning :  websites built with Omeka have all gone throught a graphic design expertise that  push the enthousiast to look more into the technology behind (Zend Framework). As such the tool fits perfectly into its mission statement : “web platform for publishing collections and exhibitions online. Designed for cultural institutions, enthusiasts, and educators, Omeka is easy to install and modify and facilitates community-building around collections and exhibits.

Generate code for Zend Framework

Can Zend Framework do scaffolding like Symfony or Cake ? No, would you say after downloading the framework and trying out. But a quick search out there shows that you’re not the only one thinking about it. In fact there are many code generators out there for PHP   : look out for Codecharge, codeigniter, or any cakephp like framework. What was missing was code specific for Zend Framework, which offers the great advantage of being developped actively and offers new versions often. A quick browse on french developers forum popped up a few applications to be tested, and looking a bit further I found some interesting implementations of scaffolding for Zend Framework :

Web developers, have a look at tine 2.0

For those interested in developping the best possible web based application, Tine2.0, formerly eGroupWare2.0, a combination of CRM and ERP,  is worth having a look at. Its multiple feature interface is one of the most intuitive multi panel screen you can imagine, built entirely out of javascript and HTML. Based on Extjs and Zend Framework, it demonstrates that those 2 popular technologies can -finally- work together to build sensible opensource applications with features of most sophisticated desktops : accordion menu that browses between various parts of the application, tere based menu for hierachical structures, dynamic grid for data scrolling, simultaneous record viewing below the data grid. The fact that the source code of Tine2.0 can be downloaded separately from packages you might already have installed ten times on your server will save you the hassle of finding interesting code lines. But i’s not only design we’re after here : PDF export at right click on  TIne2.0 contact management. More technical details would only bring enthusiasts on the project, especially after a quick look at developpers’WIKI where specific  conceptual choices are explained : MVC or not MVC, that is the question. Anyhow, when Rich Internet Applications is what you’re looking for, try out Tine20 !!

Zend Framework scaffolding, what’s cooking

The power of a framework is not often based on the speed at which it enables you to build applications :  the reason behind choices for using frameworks are often historical or political. In spite of this, as a developer, chosing a framework relies a lot on the ability to move from a model (database schema for instance) to a full CRUD  (Create-Read-Update-Delete) or BREAD (Browse-Read-Edit-Add-Delete) application. While Zend Framework does not seem ready for what we call scaffolding -quick buiding of interfaces from model-, quite a lot of people have thought about it and started working on it : it’s worth haveing a look at and using as a start if you want to go further with Zend Framework and MVC development

 

  • EdwinV from Nederlands worked on the subject 2 years ago. his blog article is still interesting and provides a start for Zend Framework scaffolding. The zip works fine but requires you to create views for each table.
  • Whitewashing, another blog entry from germany, extends the  Zend_Controller_Action which uses   a Zend_Db_Table_Abstract model to generate lists, forms and links for BREAD. Author was inspired by codecaine, another very interesting Zend Framework blog.
  • Avesta is an out of date product built on top of Zend Framework

Digitalus CMS : for ZEND framework and Jquery addicts

It’s always hard to choose when having to develop CMS based websites : there are litteraly thousands of solutions out there, and even when you think you’ve found the ultimate software (have a look at silvertripe), a new one comes in that changes the whole story. That might be the case for Digitalus CMS, whose objective is not to be the best out there, but to provide a foundation for solid web site  development. As such it is a good start to rely on popular technologies, such as Zend Framework and Jquery. We’ll never be able  to decide which is best, because the final solution is the one that you’re the most happy to work with : as such Digitalus is good bet if you have experience with Zend framework and wish to start with basic features such as suearch engine, page and menu builders, privileges management. And in the end, software keeps evolving, but if one can judge from other features described on  Digitalus website, this one has good reason to convince you to try it out !