#native_company# #native_desc#
#native_cta#

The Benefits of Using Objects with Databases

By Sam Barnum
on May 9, 2003

We all know how to fetch a row from MySQL, read the data, and save some data back.
It’s fairly simple and straightforward, with nothing tricky is going on behind the scenes.
However, there is much to be gained by using an OOP approach to managing data in your database.
This article is a sketch of how one might design an Object-Oriented approach to managing records in a database.
All the logic inherent in your data can be encapsulated into discreet Record objects, which provide a single codebase for validation, translation, and manipulation.
With the release of Zend Engine 2 and PHP5, PHP developers will have some powerful new object oriented tools to work with, which will make this approach even more attractive.
Some of the advantages of representing your database data with objects over raw associative arrays:

  • Accessor methods allow you complete control over how attributes are read and written
  • Validation on a per-record and per-attribute level.
  • Intelligent Fetching of objects from a related table.
  • Reusable logic means that all interactions with the data is going through the same codebase, making maintenance much easier.
  • Cleaner code, with Record logic being self-contained in classes instead of in various lib files.
  • Less errors from manual data-munging and SQL query generation.

Accessor Methods

Accessors are methods that wrap (or give access to) instance variables in a class. For example, if I have a class User with an instance variable $username, I would write the accessor methods User->username() and User->setUsername() that return and set the instance variable.

<?php

class User {

    var 
$username;

    function username() {

        return 
$this->username;

    }

    function setUsername($newUsername) {

        
$this->username $newUsername;

    }

}

?>



There is a good reason for all this “extra code”.
It gives the developer (you) more flexibility to change how the guts of your class work, without breaking other php code which uses the class. Consider the following evolutionary version of our trusty User class.

  • There is no longer a $username variable, all properties are now stored in an associative array called $_data.
  • The username() accessor provides a default value if the username value is empty.
  • The setUsername() accessor validates the username before accepting the value.

1
|
2
|
3
|
4
|
5