views:

61

answers:

1

I'm using Zend Framework's Zend_Db_Table classes to fetch data from a database.

I'd like to "refine" each row I fetch from a table by adding something to it. Within a plain old SQL query I would write eg. SELECT *, dueDate<NOW() AS isOverdue. In this example, feeding an extra field to the SQL query would be possible, but sometimes it might be more suitable to do the extra stuff with PHP. Anyway, I'd use this information mainly in my views, eg. to highlight overdue items accordingly.

What would be a good place to add this isOverdue data in a ZF application? My thoughts so far:

  • finding that ZF has a built-in mechanism for this (not successful so far)
  • subclassing Zend_Db_Table_Row
  • overriding _fetch() in my Zend_Db_Table class
  • rethinking whether this is a sane pattern at all :)

As a bonus, it would be nice that I could still use ZF to update rows. Maybe this would be (another) reason for a naming convention for custom fields?

+2  A: 

Why reinventing the wheel? There's a built in functionality to do this:

$this->select()->from('your_table_name_here', array('*', 'dueDate<NOW() AS isOverdue'));

Simply specify what columns you need using the second parameter of from() function and it will generate the SQL that you need (by default, if you do not use a second parameter it generates "SELECT * FROM table" query).


PavelDubinin.com - Professional Web Development blog

Pavel Dubinin
Thanks. This solution is a good start, but it has some drawbacks. From the caller's point of view, it would be great if my Zend_Db_Table class would "just work". The caller could call eg. $Table->fetchAll() or $Table->find(...) and always get the isOverdue field. This is why I'd like to do this on the row level.Second, this only works if the extra data can be expressed with SQL. This may not always be the case.
nbr
I understand what you mean, but I believe you're trying to solve the problem from the wrong perspective. Though trying to "hack" the results at the database level can sound like a good idea, in reality it will fast turn into problems and bugs which are hard to find.Why don't you just create a class which you will use to prepare the data the way you want and then use this class at your controller? This is a normal MVC approach and I'd definetly do it that way myself.
Pavel Dubinin
Also, you can use table rows: http://framework.zend.com/manual/en/zend.db.table.row.htmlYou create a class derived from Zend_Db_Table_Row_Abstract and assign it to the table with setting its $_rowClass property.Then each time you fetch the row, this class will be retrieved and you can call its methods.I'm not a big fan of such a "magic though"
Pavel Dubinin
The problem I have with this approach is that it is not database vendor agnostic. I.e. Oracle does not have a now() function.
asgeo1