Build Database Interfaces - Lessen the Impact
(Page 3 of 4 )
Another advantage to using a DB interface is that changes to the structure of the database have less of an impact on the application. Changing a single DB interface is far easier than finding and modifying code and embedded SQL throughout an entire application.
Creating a Database Interface
There are a few general guidelines that you should follow when designing your database interface:
- Use an object oriented approach and follow OOP principles.
- Make the DB interface autonomous and with a single purpose.
- Base the DB interface on a standardized design.
Use an Object-Oriented Approach
A class should be used to create each DB interface you require. This class should be a logical (code) representation of a single database structure. The members of the class represent each column of a row. The methods of the class should perform the DML and DQL operations on the row. The example below illustrates how DDL and DQL operations are implemented through the load(), submit() and delete() methods.
<?php
class Client
{
var $clientID = 0;
var $firstName = '';
var $lastName = '';
var $emailAddress = '';
function Client() {}
function load(&$db,$clientID)
{
$DQL = 'SELECT clientID,firstName,lastName,emailAddress '.
'FROM client '.
"WHERE clientID=$clientID";
if ($row = $db->GetOne())
{
$clientID = $row[ 'clientID' ];
$firstName = $row[ 'firstName' ];
$lastName = $row[ 'lastName' ];
$emailAddress = $row[ 'emailAddress' ];
return true;
} else {
return false;
}
}
function submit(&$db)
{
// clean up the data.
$clientID = (int) $this->clientID;
$firstName = addslashes(trim( $firstName ));
$lastName = addslashes(trim( $lastName ));
$emailAddress = addslashes(trim( $emailAddress ));
if ($clientID == 0)
{
$DML = 'INSERT INTO client (clientID,firstName,lastName, '.emailAddress) VALUES (NULL,'. "'$firstName','$lastName','$emailAddress')";
if ($db->Execute($DML))
{
$this->clientID = $db->Insert_ID();
return true;
} else {
return false;
}
} else {
$DML = 'UPDATE client SET '.
"firstName = '$firstName ,' ".
"lastName = '$lastName ,' ".
"emailAddress = '$emailAddress ,' ".
"WHERE clientID= $clientID";
if ($db->Execute($db))
{
return true;
} else {
return false;
}
}
}
function delete(&$db)
{
$DML = 'DELETE FROM client WHERE clientID='.$this->clientID;
if ($db->Execute($db))
{
return true;
} else {
return false;
}
}
function getClientID()
{
return $this->clientID;
}
function setClientID($clientID)
{
$this->clientID = $clientID;
}
function getFirstName()
{
return $this->firstName;
}
function setFirstName($firstName)
{
$this->firstName = $firstName;
}
function getLastName()
{
return $this->lastName;
}
function setLastName($lastName)
{
$this->lastName = $lastName;
}
function getEmailAddress()
{
return $this->emailAddress;
}
function setEmailAddress($emailAddress)
{
$this->emailAddress = $emailAddress;
}
}
? >
Next: Autonomous >>
More Zend Articles
More By Zend