PHPBuilder - A Practical Approach to Object-Relational Mapping in PHP Page 5



RSS Twitter
Articles Application Architecture

A Practical Approach to Object-Relational Mapping in PHP - Page 5

by: PHP Builder Staff
|
March 8, 2004

Let's look at some options.
Option 1: Repeating Code
The easiest way to implement ArmedHippo's RDB methods is to first add a new column to the hippos table:
FieldTypeNotes
idintegerPrimary key
Auto increment
nametext 
num_mount_pointsinteger 
Then we can cut-and-paste Hippo::load() and Hippo::save() into ArmedHippo, and add the num_mount_points field.

<?php
//ArmedHippo methods
function load($id) {
    
$this->id $id;
    
$conn mysql_connect('localhost''hippo_user''hippo_user');
    
mysql_select_db('hippos');
    
$result mysql_query("select name,
    num_mount_points from hippos where id=$id"
);
    
$this->name mysql_result($result0'name');
    
$this->num_mount_points =  mysql_result($result0'num_mount_points');
    
application_utility_tasks();
}
function 
save() 
{
    
$conn mysql_connect('localhost''hippo_user''hippo_user');
    
mysql_select_db('hippos');
    if ( 
is_null($this->id) ) 
    {
        
//New record
        
$query "insert into hippos (name, num_mount_points)
        values ('"
.$this->name."', ".
        
$this->num_mount_points.")";
        
mysql_query($query);
        
$this->id mysql_insert_id();
    }
    else 
    {
        
//Update existing record
        
$query "update hippos set name='".$this->name."',
        num_mount_points="
.$this->num_mount_points."
        where id="
.$this->id;
        
mysql_query($query);
    }
    
application_utility_tasks();
}
?>
The save() method looks at the id property on line 15. If id is null, the method adds a new record, and gets the id number allocated to it by MySQL on line 21. If id is not null, save() uses it an a primary key value in an SQL UPDATE statement (line 25).
This will work, but loses some of the advantages of OOP. If we add a weight property to Hippo, we'll also need to change ArmedHippo::load() and ArmedHippo::save(). If we add StealthHippo, we'll introduce more code that needs to be changed as Hippo changes. Further, all versions of the load() and save() methods call application_utility_tasks() separately. If we need to change the call, the code must be updated in every place.

« Previous Page
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
9
|
10
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:

Comment:



Comment:

(Maximum characters: 1200). You have characters left.