PhpRiot
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

Custom Loaders

By default, the only way to load a record with DatabaseObject is to use the loadRecord() method. This loads a record based on the primary key field you pass in the child class’s constructor. You may want to load a record based on a username instead. This is also very easy to achieve. Basically, you build your database query, then pass it to the internal _loadRecord() method, like so:

Listing 12 listing-12.php
<?php
    class User extends DatabaseObject
    {
        /* ... other code ... */
 
        function loadRecordByUsername($username)
        {
            $query = sprintf("select %s from %s where username = '%s'",
                             join(', ', $this->getSelectFields()),
                             $this->table,
                             $this->escape($username));
 
            return $this->_loadRecord($query);
        }
    }
 
    $user = new User($db);
    $user->loadRecordByUsername('johndoe');
?>

You’ll notice the getSelectFields() method was also used. This is just a utility method to build an array of the fields in the database table. So all we do is join this list with a comma so we can select it. You could just use * instead (select * from …), but if you were to create a more advanced loader, you may perform a join to load the record, in which case you would only want to select fields from the main table (not the joined table), so this method is useful in that case.

For example, let’s say you wanted to load the first record (alphabetically by username) that linked to, say, PhpRiot (www.phpriot.com). To do this, you would need to use both the users and users_links tables to determine this, but you only want the database from the users table.

Listing 13 listing-13.php
<?php
    class User extends DatabaseObject
    {
        /* ... other code ... */
 
        function loadRecordThatLinksTo($url)
        {
            $query = sprintf("
                                select %s from users u, users_links l
                                    where l.user_id = u.user_id and l.url = '%s'
                                    order by lower(u.username) limit 1
                             ",
                             join(', ', $this->getSelectFields('u.')),
                             $this->escape($username));
 
            return $this->_loadRecord($query);
        }
    }
 
    $user = new User($db);
    $user->loadRecordThatLinksTo('http://www.phpriot.com');
?>

Note here that getSelectFields() took an argument in this case. This was a field prefix (so say username would come back as u.username since we aliased the users table by u).

In This Article


Additional Files