Value objects and data access objects with PHP 4.2.x [Reproduced]

Source: Internet
Author: User








Value objects and data access objects with PHP 4.2.xgeno Timlin introductionmy real job involves working with J2EE applications at this time. it pays the bills. I 've worked with ASP in the past and have recently (2003) gotten more into working with PHP. most of my sidework these days is data driven PHP/MySQL web sites. it's unfortunate that sidework doesn't pay the bills, Because I have found PHP to be a very powerful programming platform. my attempt here is to apply some principles and concepts that I have learned in my work with J2EE into my work with PHP. value objectsthe purpose of a value object is to represent a business entity. in it's simplest form, a Vo is a simple data mapping class that mirrors the entity as it exists in the database. A more complex VO may ineffecate other functionality in its methods. for example, a Vo may have a method that transforms it's data into an XML node or a Vo may be able to read it's data from an HTML form. the one thing the VO doesn' t have to worry about is the database. the main purpose of the Vo is to store data as the data comes in and out of the database. data Access objectsdata access objects act as the middle man between the database and the value objects. the base DAO class knows specifically how to talk to the database. the base Dao knows which database is being used, what kind of database it is and whether it's supposed to be working with MySQL _ *, MSSQL _ * or PG _ * methods. the base Dao is essential to the data layer or model part of the MVC the DaO classes that extend the base DAO class can use the base Dao's methods to select, insert, update and delete data. the extended Dao classes don't have to worry about whether they are talking to a MySQL database or a PostgreSQL database. if you switch from MySQL to PostgreSQL, you can change the base DAO class and the extended Dao's will not be affected. the extended Dao's are the business logic layer or the Controller part of the MVC. dao's and Vo's working togetherthe extended Dao classes utilize the Vo's to retrieve data and update data. if you want a single row of data from the database, based on the record's primary key value, the extended Dao will have a method that returns a single vo. the extended Dao will have a method that returns an array of VO's if you want more than one row of data. the extended Dao handles inserts, updates and deletes with methods that take a single VO as an argument. the applicationin the example code, I'm presenting some of the functionality of a simple auto sales web site. we'll look at the vehicles that are stored in the database. the database is a MySQL database and the vehicles table is created with the following properties:

CREATE TABLE `vehicles` (`vehicleid` INT NOT NULL AUTO_INCREMENT,`year` VARCHAR( 4 ) NOT NULL ,`make` VARCHAR( 25 ) NOT NULL ,`model` VARCHAR( 25 ) NOT NULL ,`color` VARCHAR( 25 ) NOT NULL ,`price` DOUBLE NOT NULL ,PRIMARY KEY ( `vehicleid` ) );
The Base Value objectthe base VO has a number of methods that assist in reading forms. another method that cocould be implemented here might be a date formatting method. different databases return date values in your different formats. to keep consistency, you may want to do some string manipulation with the date values to keep them all looking the same. the extended value objectthe vehiclevo class has five properties that reflect the five columns in the vehicles table. A default constructor exists to create an empty VO or if given arguments, a Vo filled with data:
<?php
// create a new VO
function VehicleVO($vehicleid= 0, $year= "", $make= "",
                   $model= "", $color= "", $price= 0.00) 
{
    $this->vehicleid = $vehicleid;
    $this->year = $year;
    $this->make = $make;
    $this->model = $model;
    $this->color = $color;
    $this->price = $price;
}
?>
Other methods the VO includes are:
Function equals ($ vo)-
Compares itself to another vehiclevo object. returns true or false.
Function copy ($ vo)-
Copies the contents of another vehiclevo object.
Function readform ()-
Reads values from the $ _ post array.
Function readquery ()-
Reads values from the $ _ Get array.
Function toxml ()-
Returns a string that contains it's data represented as an XML node.
Function tostring ()-
Returns a string that contains a delimited line of data.
Function getpk ()-
Return the value of the primary key field.
You can add any other methods you may need to the vo. for example, if you wanted to have a method that returned the vehicle year, make and model with the Year in red but the rest of the text Black:
<?php
function getDescription() 
{
    $buf = "<font color='#ff0000'>";
    $buf .= $this->year . "</font>";
    $buf .= "<font color='#000000'>";
    $buf .= $this->make . " " . $this . "</font>";
    return $buf;
}
?>
The base data access objectthe base Dao provides methods to the vehicledao class (and any other classes that extend it) that call database specific PHP methods to access the database. the base Dao cocould be used on it's own to provide data access on a PHP page, but in keeping with the MVC concepts, we use it as an abstract class whose methods are implemented by objects that know about specific entities in the database. the Extended Data Access objectthe vehicledao class implements the functionality of the base Dao and transfers data between vehiclevo's and the database. the constructor callthe base Dao's constructor which establishes the connection to the database.
<?php
function VehicleDAO($dbserver="", $dbname="", $dbuser="", $dbpass="") 
{
    parent::BaseDAO($dbserver, $dbname, $dbuser, $dbpass);
}
?>
The parent constructor knows the default database connection parameters, but you can specify the values in the constructor of the extended class too if you were working with multiple databases. the vehicledao object keeps it's own simple SQL queries. this makes the data access methods easier to implement. the select queries are made to allow you to append your own where clause parameters, order by clses and limit clses (For MySQL ). the data manipulation SQL statements are formatted so that it takes little extra code inside the data access methods to set the values to be inserted or updated.
<?php
var $SQL_SELECT = "SELECT * FROM `vehicles` ";
var $SQL_COUNT = "SELECT count(*) AS cnt FROM `vehicles` ";
// insert with no value for an auto_increment field.
var $SQL_INSERT = "INSERT INTO `vehicles` (year,make,model,color,price) VALUES ('%A','%B','%C','%D',%E)";
var $SQL_UPDATE = "UPDATE `vehicles` SET ";
var $SQL_DELETE = "DELETE FROM `vehicles` WHERE vehicleid=%A";
?>
The vehicledao object contains a number of data access methods:
Function findbypk ($ vehicleid)-
Returns a single vehiclevo object based on the $ vehicle ID or null if no record is found.
Function findbysql ($ SQL, $ orderby = "")-
Returns an ordered array of vehiclevo's based on a complete SQL query.
For example:
<?php

$dao = new VehicleDAO();
$volist = $dao->findBySQL("select * from vehicles where make='Ford' ", "year, model");
foreach($volist as $vo) 
{
    echo("$vo->year $vo->model $vo->color<br />");
}
?>
The above wowould produce a list of Ford vehicles ordered by year and model.

Function findwhere ($ where = "", $ orderby = "")-
Returns an array of vehiclevo's based on where clause fragments.
For example:
<?php

$dao = new VehicleDAO();
$volist = $dao->findWhere("(year > '1999') AND (make='Ford')");
foreach($volist as $vo) 
{
    echo("$vo->year $vo->model $vo->color<br />");
}
?>
The above wowould produce a list of Ford vehicles made in the year 2000 or later. You can easily add your own data access custom methods:
<?php
function findByPrice($price, $gtlt) 
{
    $this->sql = $this->SQL_SELECT;
    $voList = array();
    $where = "WHERE ( price $gtlt $price) ";  
    $this->sql .= $where;
    $this->exec($this->sql);
    while($row = $this->getObject()) 
    {
        $vo = new VehicleVO(
            $row->vehicleid, 
            $row->year, 
            $row->make, 
            $row->model, 
            $row->color, 
            $row->price
            );
        array_push($voList, $vo);
    }
    return $voList;
}
?>
Then to use the custom method:
<?php
$dao = new VehicleDAO();
$volist = $dao->findByPrice(5000, "<");
foreach($volist as $vo) 
{
    echo($vo->getDescriptiion() . "<br />");
}
?>
The above wowould produce a list of Ford vehicles whose price was less than $ 5000.the data manipulation methods are simple and use VO objects to add, update or remove data.

Function insertvo ($ vo)-
Inserts the data from a vehiclevo into the database. returns the number of rows affected.
Function updatevo ($ vo)-
Updates a record based on the value of $ vo-> vehicleid. returns the number of rows affected.
Function deletevo ($ vo)-
Deletes a record based on the value of $ vo-> vehicleid. returns the number of rows affected.
Putting it all togetaskapplist. php, we create a list of vehicles and display them to the user.
<?php  
$dao = new VehicleDAO();
$volist = $dao->findWhere("", "make, year LIMIT 0, 25");
foreach($volist as $vo) 
{
    echo("<tr><td><a href='appedit.php?vid=$vo->vehicleid'>$vo->vehicleid</a></td>");
    echo("<td>$vo->make</td><td>$vo->year</td><td>$vo->model</td>
          <td>$vo->color</td></tr>");
}
...
?>
Clicking on the vehicle ID link takes the user to the vehicle_edit.php page. In appedit. php we display a form loaded with the vehicle data. The form posts to the appupdate. php script.
<?php
$id = $_GET["id"];
$dao = new VehicleDAO();
$vo = $dao->findByPK($id);
...
    <input type="text" name="year" value="<?=$vo->year?>" />
    <input type="text" name="model" value="<?=$vo->model?>" />
    <input type="text" name="color" value="<?=$vo->color?>" />
...
?>
In appupdate. php, we create an empty vehiclevo object and read in the data from the form. The vo is then passed to the update () method of a vehicledao object.
<?php

$vo = new VehicleVO();
$dao = new VehicleDAO();
$vo->readForm();
$records_updated = $dao->update($vo);
...
?>
Summarynow this is not the pure model/View/controller design that J2EE developers are all drooling over these days, but it's close enough for horseshoes. I am sure that with PHP 5 deeper Object Oriented capabilities, a better MVC design will arise. but I believe this is a pretty good Object Oriented Design for now. also, I 've got ded a PHP page that builds the vo and Dao classes for you. how much E Asier can you get it? Geno Timlin

  • Table def Dao
  • Vehicledao
  • Basedao
  • Basedao-MySQL
  • Basedao-pgsql

Original article address:
Http://www.phpbuilder.com/columns/timlin20040528.php3? Print_mode = 1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.