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

Creating The User DatabaseObject Class

In the previous section, we looked at a class called User for manipulating a database table called users. We will now look at how this class is structured. Further on, we will add more advanced functionality to this class to demonstrate the other aspects of DatabaseObject.

Here is the User class at its most basic:

Listing 1 listing-1.php
    class User extends DatabaseObject
        function User(&$conn)
            parent::DatabaseObject($conn, DBO_POSTGRESQL, 'users', 'user_id');
            $this->setType('active', DBO_TYPE_BOOLEAN);
            $this->setType('ts_created', DBO_TYPE_TIMESTAMP);
            $this->setProperty('active', true);
            $this->setProperty('ts_created', time());

There are a few key things we did here, which I will now explain.

Firstly, we accept a parameter called $conn. This should be the returned value from your pg_connect() or mysql_connect() call. You are probably using a database abstraction class anyway, so you may want to modify the source code to use your database abstraction. For the purposes of this article, we’ll assume you’re not.

Next, we call the DatabaseObject constructor, which involves passing the $db object, as well as the database table name (users), and the primary key field for this table (user_id). Also, since we’re assuming you’re not using database abstraction, we also need to pass in the database server type so we know which functions to use. This would be DBO_POSTGRESQL for PostgreSQL and DBO_MYSQL for MySQL.

The next step is to define the columns in this table (all columns except for the primary key, which we already specified). This list could be dynamically generated, however, this would be an unnecessary performance hit, considering how infrequently the database structure will change.

On the next two lines, we define the active column as a Boolean, and the ts_created column as a timestamp. The reason for this is that these two types are treated slightly differently from other types of columns. It allows us to set values using the time() call, or to set Boolean values just using true or false. Note that you should only use the timestamp type for timestamp fields (i.e. not fields that are just date or time fields). Additionally, since UNIX timestamps are used internally, the dates stored here must be post-1970. If they are to be earlier (e.g. for peoples’ date of birth), you will need to manipulate these values manually.

At time of writing, the only column types that need to be set with the setType() method are Booleans and timestamps.

The final thing we do in this code is set the default value for the ts_created field to be “now”.

In This Article

Additional Files