Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Managing Your Data With DatabaseObject


DatabaseObject is a class I wrote three or four years ago, as a way of easily manipulating database data. It is not a replacement for a database abstraction class. In fact, it works very nicely with a database abstraction class, however, the version we have provided uses the native PHP PostgreSQL and MySQL database calls.

You will need to download this file in order to follow the examples in this article.

Note: My book uses an updated version of DatabaseObject which has been redesigned for PHP 5 and with slightly different function names. While both versions work fundamentally the same, they cannot be interchanged without updating the code that uses the class.

The basic idea is that for each “main” table in your database, there exists a class which is used to control the data in that table. So rather than fetching a record with an SQL select statement, you would call the loadRecord() method. Similarly, there is a saveRecord() method for inserting or updating data, and a deleteRecord() method for deleting data.

This article goes over the DatabaseObject class, showing you how to apply it to your own development work. The examples presented here are performed in PostgreSQL and MySQL, however the ideas here will work with other database servers with only a little modification to the class.

The items that will be covered in this article include:

  • Creating a database structure that is compatible with DatabaseObject
  • Creating a custom DatabaseObject class for your table(s)
  • Setting column names and types for your class
  • Setters, getters and checkers
  • Callbacks

All of this functionality will be centred around a user management system. A user can be created, edit, deleted or loaded. Additionally, a user can store a list of their favourite web links. This secondary idea is not fundamental to DatabaseObject, but it will help demonstrate further extension of the system (such as effectively using callbacks and performing custom database queries).

In This Article

Additional Files