views:

32

answers:

1

I think it's possible to write select queries with either Zend_Db_Select or Zend_Db_Table_Abstract, but I don't understand when to use which of the two.

Is one more optimized for something than the other? Are joins "easier" with one or the other?

Thanks!

+4  A: 

There are a few different options in producing queries, for historical reasons.

In early versions of Zend Framework, Zend_Db_Tables had a method fetchAll with parameters where, order, offset and limit which you could use to fetch rows from a table. Developers soon found limitations with this approach. How would you add a GROUP BY clause?

Zend_Db_Select was invented to solve this problem, and you'll notice that since ZF 1.5, the fetchAll and related methods accept a Zend_Db_Select instance as the first parameter. Using the other parameters of fetchAll is now deprecated and you should pass in either an SQL string or a Zend_Db_Select object.

A Zend_Db_Select is simply a programmatic interface for building an SQL query. It's great for changing parts of the SQL based on user input or different factors, as instead of manipulating strings, you can just change the method calls and arguments.

Zend_Db_Table will return a Zend_Db_Table_Select (a Zend_Db_Select subclass) instance with its table name predefined if you call its select method - this is about the only difference between Zend_Db_Select and Zend_Db_Table_Select.

Your consideration really is whether to use Zend_Db_Select or to write SQL manually. Zend_Db_Select isn't infinitely flexible but it is easy to read, manipulate and work with.

David Caunt
+1 Great Explanation
tawfekov
Great answer! I sort of suspected some "history" was behind this duplicate functionality :)
Niels Bom
I think ZF2 will offer much cleaner database functionality. Zend_Db_Table is not particularly popular any more because it implements Active Record, a pattern which most have dumped in preference of Data Mappers.
David Caunt
@David Caunt, Active Record is the DB-pattern used in Rails, right? I looked it up and Rails 3 will continue with ActiveRecord which would suggest it's not dead yet. Do you have some sources for the "dumping of Active Record"?
Niels Bom
Sorry, I should have been clearer. In some PHP circles, Active Record has been replaced with Data Mappers as it's generally seen as a better architected and more flexible solution. This is true of Doctrine 2 and Zend Framework 2 (though in ZF2 I think it'll be recommend to use Doctrine or Propel). In Active Record, an object is coupled to a row and its persistence method, with Data Mapping another object handles persistence of data using accessors. See http://martinfowler.com/eaaCatalog/activeRecord.html and http://martinfowler.com/eaaCatalog/dataMapper.html
David Caunt