#native_company# #native_desc#
#native_cta#

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

By PHP Builder Staff
on March 8, 2004

Option 4: A New Base Class
Fortunately, there’s a way out. Suppose we introduce a new class, called BusinessBase,
and make it the base class of all business classes. BusinessBase performs the application
utility tasks (permissions, transaction logging, etc.). It also handles every SQL statement.
None of the business classes ever connect to a database directly. Instead, they use a data
structure to exchange information with BusinessBase.
Here’s the new Hippo:

<?php

class Hippo extends BusinessBase 

{

    var 
$id null;

    var 
$name null;

    
//Constructor

    
function Hippo() 

    {

        
$this->table_name 'hippos';

        
$this->addField('id', new DataField(DataField::TYPE_NUMERIC(), true) );

        
$this->addField('name', new DataField(DataField::TYPE_STRING(), false) );

    }

    
//Load record from DB

    
function load($id

    {

        
parent::load($id);

        
$this->id $this->getDBValue('id');

        
$this->name $this->getDBValue('name');

    }    

    
//Save record to DB

    
function save() {

    
$this->setDBValue('id'$this->id );

    
$this->setDBValue('name'$this->name );

    
parent::save();

    
//Get id number supplied by INSERT

    
$this->id $this->getDBValue('id');

    }

}

?>



The Hippo constructor creates the data structure that exchanges information with BusinessBase.
First, it sets the name of the RDB table used to store hippo data (line 6). Then it specifies
each field in the table, supplying the name of the field, and a DataField object (lines 7 and 8).
A DataField object contains the data type of a field, and a flag showing whether or not it is
the primary key.
Hippo::load() passes a record id to
BusinessBase::load() (line 12), then extracts the values it needs
(id and name in this case, in lines 13 and 14). Hippo::save()
stores the values it wants to save (lines 18 and 19), and calls BusinessBase::save()
(line 20). If Hippo::save() is creating a new record,
BusinessBase::save() supplies its id number, which
Hippo::save() then retrieves (line 22).

1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
9
|