Home arrow PHP arrow Page 4 - Sub Classing Exceptions in PHP 5

Modifying the MySQL class's signature to trigger customized exceptions - PHP

If you do any serious programming, whether it's in PHP 5 or some other language, you've needed to know how to handle run time errors and other "exceptional" conditions. You can do this by making your program throw generic exceptions. Or you can unlock the potential of PHP 5 and learn how to create custom exceptions, which is the subject of this four-part series.

TABLE OF CONTENTS:
  1. Sub Classing Exceptions in PHP 5
  2. Getting started with exceptions with PHP 5
  3. Catching MySQL-related exceptions with the PHP 5 Exception class
  4. Modifying the MySQL class's signature to trigger customized exceptions
By: Alejandro Gervasio
Rating: starstarstarstarstar / 4
October 15, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

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: