#native_company# #native_desc#

The Benefits of Using Objects with Databases Page 2

By Sam Barnum
on May 9, 2003


class User {

$_data = array(); // associative array containing all the attributes for the User

    function username() {

        return !empty(
$this->_data['username']) ? $this->_data['username'] : '(no name!)';


    function setUsername($newUsername) {

        if (
$this->validateUsername($newUsername)) {

$this->_data['username'] = $newUsername;



    function validateUsername(&$someName) {

        if (
strlen($someName) > 12) {

            throw new 
Exception('Your username is too long'); // PHP5 only






Obviously, this gives tremendous control over how to access the properties of an object. If a programmer had accessed the username property directly, the changes above would have broken her code. By using the accessor methods, however, the code referencing our User class gets the additional validation functionality without changing anything.
Note that the username validation code is in a separate method from the setUsername() method.
This will come in handy when validating the object before saving to the database.
Also, it’s a good rule of thumb that the less a method or class needs to do, the more reusable it will be.
This is even more apparent when you start subclassing, and want to override a specific part of a class’s parent behavior.
If the methods are small and specific, this is a snap.
If the methods are bloated and multipurpose, you will probably end up duplicating a lot of the super class code in your subclasses.
For instance, suppose Admin is a subclass of User. There may be a different, less lenient method for validating passwords for admin users.
Better to only override the validation method then the entire setUsername() method.