Sr. Web Developer
mediabistro.com
US-NY-New York

Justtechjobs.com Post A Job | Post A Resume

The Benefits of Using Objects with Databases

<?php
class User {
    var
$_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
        
}
        return
true;
    }
}
?>
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.
Next Page

[Page 1]  [Page 2]  


Comments:
Copied Articlearul rajesh07/01/03 17:10
part deux?t farnham06/23/03 18:13
great articleZachary06/01/03 17:56
great articleTerry Gilliam05/13/03 20:56
Excellent articleVic Fryzel05/12/03 15:27
Object databasesBenjamin Stiglitz05/12/03 13:57
SourceSam Barnum05/12/03 12:32
 

If you are looking for help, please post on the appropriate forum here. Your questions will be answered much more quickly.

Add A Comment:

Name:

Email:

Subject:

Message:

To reduce spam posts, messages are now manually approved

You are not [logged in]. That means your account will not get credit for this post.