Home arrow PHP arrow Page 3 - Building Object-Oriented Database Interfaces in PHP: Updating the Application to PHP 5

Using the class in a object-oriented scenario: the "try" and "catch" blocks - PHP

In this fourth and final article in the tutorial series, Alejandro Gervasio updates the "DBIGenerator" class developed in the previous articles. The new version incorporates features in PHP 5, such as member visibility, exceptions, and other useful items.

TABLE OF CONTENTS:
  1. Building Object-Oriented Database Interfaces in PHP: Updating the Application to PHP 5
  2. Porting Database Interfaces to PHP 5: member visibility, exceptions and more
  3. Using the class in a object-oriented scenario: the "try" and "catch" blocks
  4. Completing the round: updating and deleting rows
By: Alejandro Gervasio
Rating: starstarstarstarstar / 15
August 31, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

As I said before, updating the code to work in PHP 5 is really simple. I'll build several examples that demonstrate the use of the "DBIGenerator" class, performing single-row DML operations on a sample "users" database table. Although I've thoroughly implemented these operations in my previous articles, in this case I'll take advantage of some handy PHP 5 capabilities, for inserting, updating and deleting table rows.

The first example simply adds a new row to the sample "users" table, as listed below:

// include class files
function __autoload($class_name) {
    require_once 'classes/'.$class_name.'class.php5';
}
try {
    // connect to MySQL
    $db=new MySQL(array('host'=>'host','user'=>'user','password'=>
          
'password','database'=>'databasename'));
    // instantiate a new DBIGenerator object
    $gn=new DBIgenerator('users','user','classes/');
    // generate class file
    $gn->generate();
    // get $user object
    $user=$gn->getObject();
    // set object properties
    $user->setfirstname('John');
    $user->setlastname('Coffey');
    // insert row into table
    $user->submit();
    echo 'Row successfully inserted';
}
catch (Exception $e){
    echo $e->getMessage();
    exit();
}

If you've read the previous parts of this series (I hope you did), the above example is very understandable. We use the "DBIGenerator" class to create on the fly a "user" database interface within the "classes/" directory. This class is used to directly "interface" with the "users" table, by providing a single access point to it.

After calling the "generate()" method, the "user" DB interface class is built transparently on the background, and defined as follows:

class user{
    private $id='';
    private $firstname='';
    private $lastname='';
    public function __construct(){}
    public function setid($id){
        $this->id=$id;
    }
    public function getid(){
        return $this->id;
    }
    public function setfirstname($firstname){
        $this->firstname=$firstname;
    }
    public function getfirstname(){
        return $this->firstname;
    }
    public function setlastname($lastname){
        $this->lastname=$lastname;
    }
    public function getlastname(){
        return $this->lastname;
    }
    public function load(){
        $r=mysql_query("SELECT * FROM users WHERE id='$this->id'");
        return mysql_fetch_array($r,MYSQL_ASSOC);
    }
    public function submit(){
        mysql_query("INSERT INTO users SET firstname='$this->
            firstname',lastname='$this->lastname'");
        $this->id=mysql_insert_id();
    }
    public function update(){
        mysql_query("UPDATE users SET firstname='$this->
            firstname',lastname='$this->lastname' WHERE id='$this->id'");
    }
    public function delete(){
        mysql_query("DELETE FROM users WHERE id='$this->id'");
    }
}

As you can see, the class is generated by specifying the visibility for the data members, which are declared as private, and the respective methods, that are set to be public. The rest of the code remains nearly identical to the PHP 4 version.

However, let's focus our attention on the snippet that adds a row to the "users" table. The first thing to note is that we're including the required class files using the "__autoload()" function:

// include class files
function __autoload($class_name) {
    require_once 'classes/'.$class_name.'class.php5';
}
 

This function is very useful for automatically loading the necessary class files, whenever we try to instantiate an object from a given class, without the need to code multiple "require_once()" statements. Of course, the class file could have been included in the traditional way, but in this example I decided to use this handy function.

The last relevant issue within the code is the usage of the "try-catch" blocks, for handling potential runtime errors. If you have a background in Java, these blocks should already be familiar. However, if they're unknown to you, take it easy, because I'll give a short explanation of their meaning.

Take into account that the "DBIGenerator" class throws a new Exception object when an error condition occurs, such as performing the query to obtain the field names of the table, or writing the class code to a file. Similarly, the MySQL abstraction class throws the proper exceptions when connecting and selecting the specified database. Doing so, we've wrapped the code into a "try" block, and defined another "catch" block to handle all of the exceptions.

In this particular case, I've chosen to pass to the constructor of the Exception class a simple error message that will be displayed before exiting the script. Since this class provides the "getMessage()" method, we're able to use it to show the messages, like this:

catch (Exception $e){
    echo $e->getMessage();
    exit();
}
 

Certainly, we could have gone further in handling an error condition (i.e. writing the error to a log file). However, in order to give a quick introduction to Exceptions in PHP, it's more than enough.

To end this overview, once the $user object is made available within the script, we add a new row to the table by simply setting the values for the "firstname" and "lastname" fields, and lastly inserting the data through the "submit()" method:

 $user=$gn->getObject();
 // set object properties
 $user->setfirstname('John');
 $user->setlastname('Coffey');
 // insert row into table
 $user->submit();
echo 'Row successfully inserted';

Okay, I think that was really easy, huh? In the next few lines we'll describe the process for updating and deleting a table row. Keep reading.



 
 
>>> 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: