In the course of the previous section you hopefully learned how to build a basic MySQL abstraction class that is capable of throwing some customized exceptions of type "MySQLException" to client code. The next step we will take, then, consists of deriving a subclass from the base "Exception" class included with PHP 5. This subclass will be responsible for handling the aforementioned customized MySQL exceptions. That being explained, please take a look at the following sample code. It demonstrates how to build a specific exception class by using raw inheritance. Here it is: // extend the built-in exception class to throw MySQL-related exceptions class MySQLException extends Exception{ public function __construct($message,$code=0){ // call parent of Exception class parent::__construct($message,$code); } public function showExceptionInfo(){ return 'Catching MySQL exceptions...<br />Exception message: '.$this->getMessage().'<br />Source filename of exception: '.$this->getFile().'<br />Source line of exception: '.$this->getLine(); } } As you can see, things are becoming really interesting. In the above example, I simply derived a subclass from the native "Exception" parent available in PHP 5, in order to intercept all of the exceptions of type "MySQLException." In this particular case, this child class defines and implements a brand new method called "ShowExceptionInfo()," which is admittedly fairly basic. However, it really comes in handy for demonstrating how to extend the functionality of the native exception mechanism offered by PHP 5, by the basic means of inheritance. Pretty simple to grasp, right? So far, so good. At this stage you hopefully learned how to build a customized class that has the ability for handling exceptions other than the generic ones provided natively by PHP 5. Thus, in summary, on one hand I built a MySQL abstraction class that's capable of triggering a few custom exceptions of type "MySQLException" to client code, while on the other hand there's a specific class whose task is to handle these specific exceptions. Undoubtedly, at this point you must be wondering how these two independent classes can be linked with each other in a useful fashion. And the answer is very simple, actually: by way of a simple "try-catch()" block! As you can see, it's extremely easy to build a custom exception mechanism with PHP 5 by simply extending the functionality of its base "Exception" class with inheritance. Nonetheless, I'm pretty sure that you'll grasp how the "MySQLException" sub class does its thing much more easily if I show you an illustrative hands-on example. Bearing in mind this idea, in the section to come I'm going to built this concrete example for you, so you can learn very quickly how to implement a custom exception mechanism with PHP 5. Go ahead and read the next few lines. I'll be there, waiting for you.
blog comments powered by Disqus |
|
|
|
|
|
|
|