Introduction to creating a data layer with Zend Framework

I’m considering Zend Framework data access classes very helpful to programming application’s data layer. It simplifies a lot of common operations by providing us with good shortcuts for them. This post briefly describes how to design a data layer of your application with Zend_Db_Table.

The key concept of creating a data layer is creating classes that represent database objects, such as tables and stored procedures. In other words, when you have a database table, called “user_info”, which stores information about registered users, then you need to create the “UserInfo” class that encapsulates all common operations with the “user” object. This class should contain methods for creating, modifying and deleting users, and for finding users by some criteria. Optionally, it may have methods for duplicating “user” object and specific maintenance operations.

The classes of data layer should implements the same common interfaces because they need to share the same technique for data management operations (for inserting, updating, deleting and fetching rows). The classes also encapsulate validation and generalize database error handling.

Zend Framework contains the following classes for data layers developing:

  • Zend_Db_Adapter is an adapter of application’s data source (a database, in most of the cases). In other words, it provides the developer with one common interface that encapsulates differences in implementation of common operations for various databases. With Zend_Db_Adapter the developers can prepare and run queries, use transactions, modify database data.
  • Zend_Db_Table represents one database table (either logical or physical) in the application’s data source. It encapsulates data validation and “business logic”. A set of Zend_Db_Table descendants forms the application’s data layer that serves as the boundary between database server, such as MySql or SQLite, and application’s view classes.
  • Zend_Db_Select, Zend_Db_Row, Zend_Db_Table_Rowset are auxiliary classes, which aid in accessing and modifying properties of data records during manipulating and fetching records from the table.

For each table, which you are planning to use in your application, you can create corresponding class by extending Zend_Db_Table object and, whether it necessary, overwrite insert, update and delete methods by adding application-specific calculations and/or validations. Moreover, you can extend already created table class--this fairly simplifies (and makes data layer more organized) object creation for similar tables. For example, when you need similar validation for two different tables, you can create a descendant of Zend_Db_Table with the validation and then create desired table-mapping classes by extending this class.