Home arrow PHP arrow Page 4 - Building Object-Oriented Database Interfaces in PHP: Abstracting Database Tables

Getting closer: a detailed look at the "generate()' method - PHP

Welcome to part two of the series "Building Object-Oriented Database Interfaces in PHP." In the previous article, I offered complete coverage of the role that database interfaces play in Web applications, highlighting the immediate benefits of having a centralized mechanism for accessing, processing and verifying data, within an object-oriented environment. The "DBIGenerator" class I showed for demonstration purposes in the first article doesn't scale well in real applications. In this article, we will start solving its problems with a revamped version of the class.

TABLE OF CONTENTS:
  1. Building Object-Oriented Database Interfaces in PHP: Abstracting Database Tables
  2. Turning back time: a quick look at the older "DBIGenerator" class
  3. Working with multiple database interfaces: improving the "DBIGenerator" class
  4. Getting closer: a detailed look at the "generate()' method
  5. Updating and deleting a row: the "update()" and "delete()" methods
  6. Spotting the differences: the new "DBIGenerator" class in practice
By: Alejandro Gervasio
Rating: starstarstarstarstar / 13
August 17, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

This method is the most resource intensive, since it dynamically generates the class file that will interface with a database table. In general terms, the class file is built by concatenating strings, so the generation process shouldn't present any difficulties to being understood.

First, the method obtains the field names of the table passed to the class, assigning them directly as class properties, storing temporarily the output in the $methods variable, to be included at a later time. The lines below perform these operations:

// build class header

$str='<?php class '.$this->name.'{';

if(!$result=mysql_query("SHOW COLUMNS FROM $this->table")){

die('Could not run query '.mysql_error());

}

// build data member declaration

if(mysql_num_rows($result)>0){

while($row=mysql_fetch_array($result,MYSQL_ASSOC)){

$str.='var $'.$row['Field'].'=\'\';';

$methods.='function set'.$row['Field'].'($'.$row['Field'].')
{$this->'.$row['Field'].'=$'.$row['Field'].';}';

$methods.='function get'.$row['Field'].'(){return $this-
>'.$row['Field'].';}';

// store field names in array

$fields[]=$row['Field'];

}

}

Then, the class constructor is generated with this single line:

$str.='function '.$this->name.'(){}';

Finally, the accessors and modifiers methods are appended to the output, like this:

// build modifiers and accessors

$str.=$methods;

The next step is to append the "load()" and "submit()" methods to the output string, accomplishing the "SELECT" and "INSERT" single-row operations. They're defined as listed below:

// build load() method

$str.='function load(){$r=mysql_query("SELECT * FROM
'.$this->table.' WHERE id=\'$this->id\'");';

$str.='return mysql_fetch_array($r,MYSQL_ASSOC);}';

// build submit() method

$str.='function submit(){mysql_query("INSERT INTO '.$this-
>table.' SET ';

foreach($fields as $field){

$str.=($field!='id')?$field.'=\'$this->'.$field.'\',':'';

}

$str.='");$this->id=mysql_insert_id();';

$str=preg_replace("/,\"/","\"",$str).'}';

Notice that in this case, we're using the native MySQL functions to execute queries and retrieve a row. However, this condition might be easily changed by utilizing methods provided by another object.

So far, so good. We've already described the two main methods used to retrieve and insert a row into the database table. Our next task is to explain the remaining methods, "update()" and "delete()". Don't you worry, because they're just a few lines away.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: