Thursday 8 April 2010

Poor man's Model in PHP, Smarty and ADODB

Model-View-Controller (MVC) is a well-established architecture in web applications. If you are not using an established framework for your web app because it's a small app, it still pays to adopt some features of MVC because it makes your app cleaner.


If you are using a templating language like Smarty with PHP, you are getting some of the View aspect. I recently realised that there is a simple way to get a Model of sorts. Now typically with Smarty you would do a whole lot of assignments like this to pass values into the View:




$page->assign('empid', $empid);
$page->assign('empname', $empname);



I realised that with ADODB (or ADODBLite) I could turn on associative fetch, which makes the DB SELECT statement return rows of hashes, e.g.




$employee = Array('id' => '101', 'name' => 'Joe Bloggs', ...)



Then you pass the whole array into a Smarty template like this with one assignment, instead of one for each field.




$page->assign('employee', $employee);



Inside the template you can refer to the fields as:




{$employee.id} {$employee.name}



But that's not all. You can also get the input fields to return values in an array, like this:




<input name="employee[name]" title="Employee name" type="text" value='{$employee.name|escape:"quotes"}' />
In the PHP, you would get the array of values with:


$employee = $_REQUEST['employee'];
and it's an associative array similar to what you put in. You can even, with care, use that array to build an INSERT or UPDATE query for the database. What you have to watch out for is that the array has both numeric and symbolic keys when ADODB returns it. You can also use that array to carry other fields such as error flags and messages, provided you are careful not to try to write those back to the database. One way would be to filter out keys of a particular form, say those starting with _. In some of that HTML above you should take care to apply htmlspecialchars() or the Smarty modifier "escape" as necessary.

No comments:

Post a Comment