PHP
  Home arrow PHP arrow Page 4 - Sub Classing Exceptions in PHP 5
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

Sub Classing Exceptions in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 3
    2008-10-15


    Table of Contents:
  • Sub Classing Exceptions in PHP 5
  • Getting started with exceptions with PHP 5
  • Catching MySQL-related exceptions with the PHP 5 Exception class
  • Modifying the MySQL class's signature to trigger customized exceptions

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Sub Classing Exceptions in PHP 5 - Modifying the MySQL class's signature to trigger customized exceptions
    ( Page 4 of 4 )

    As I mentioned earlier, it’s perfectly possible to extend the native “Exception” class provided by PHP 5 to create some customized exceptions, which can be used to handle different error conditions in a separate way.

    This exception sub classing process is composed basically of two steps. The first one requires us to provide certain classes with the capacity for triggering customized exceptions, while the second one sees us creating one or more subclasses from the parent “Exception.”

    Particularly, in this final section of this tutorial I’m going to show you how to modify the signature of the “MySQL” class that you saw before, so it can launch some custom exceptions to client code. The remaining task, that is, extending the pertinent base “Exception” class, will be discussed in the next tutorial.

    All right, now that I have clarified that point, please take a look at the modified definition of the aforementioned “MySQL” class below. It is now capable of triggering a customized “MySQLException.”


    // define 'MySQL' class

    class MySQL{

    private $conId;

    private $host;

    private $user;

    private $password;

    private $database;

    private $result;

    const OPTIONS=4;

    public function __construct($options=array()){

    if(count($options)!=self::OPTIONS){

    throw new MySQLException('Invalid number of connection parameters');

    }

    foreach($options as $parameter=>$value){

    if(!$value){

    throw new MySQLException('Invalid parameter '.$parameter);

    }

    $this->{$parameter}=$value;

    }

    $this->connectDB();

    }

    // connect to MySQL

    private function connectDB(){

    if(!$this->conId=mysql_connect($this->host,$this->user,$this->password)){

    throw new MySQLException('Error connecting to the server');

    }

    if(!mysql_select_db($this->database,$this->conId)){

    throw new MySQLException('Error selecting database');

    }

    }

    // run query

    public function query($query){

    if(!$this->result=mysql_query($query,$this->conId)){

    throw new MySQLException('Error performing query '.$query);

    }

    return new Result($this,$this->result);

    }

    }


    // define 'Result' class

    class Result {

    private $mysql;

    private $result;

    public function __construct($mysql,$result){

    $this->mysql=$mysql;

    $this->result=$result;

    }

    // fetch row

    public function fetchRow(){

    if(!$row=mysql_fetch_assoc($this->result)){

    return false;

    }

    return $row;

    }

    // count rows

    public function countRows(){

    if(!$rows=mysql_num_rows($this->result)){

    throw new Exception('Error counting rows');

    }

    return $rows;

    }

    // count affected rows

    public function countAffectedRows(){

    if(!$rows=mysql_affected_rows($this->mysql->conId)){

    throw new Exception('Error counting affected rows');

    }

    return $rows;

    }

    // get ID of last-inserted row

    public function getInsertID(){

    if(!$id=mysql_insert_id($this->mysql->conId)){

    throw new Exception('Error getting ID');

    }

    return $id;

     }

    // seek row

    public function seekRow($row=0){

    if(!is_int($row)||$row<0){

    throw new Exception('Invalid result set offset');

    }

    if(!mysql_data_seek($this->result,$row)){

    throw new Exception('Error seeking data');

    }

    }

    }


    That wasn’t hard to grasp, right? As you can see, the previous “MySQL” class now has the ability to throw a specific “MySQLException,” which certainly helps to improve the way that certain errors conditions are handled. In this case, one “try-catch” block could be used for processing only generic exceptions, and a different one would handle specifically those of type “MySQLException.”

    But I’m getting ahead of myself, since this process will be discussed in depth in the next part of the series. In the meantime, feel free to use all of the sample classes listed earlier, and try to develop your own customized exceptions.

    Final thoughts

    In this first installment of the series, you hopefully learned the basic concepts that surround the implementation of generic exceptions with PHP 5. Besides, you saw how to build, in a few simple steps, a sample class that can throw customized exceptions.

    Logically, it’s necessary to demonstrate not only how to create these specific exceptions, but how they can be intercepted within a particular “try-catch” block. However, these useful topics will be discussed in detail in the next article, so you don’t have any excuses to miss it!



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

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek