CHAPTER 15 ■ AN INTRODUCTION TO PEAR AND PYRUS
class MyFeedClient {
function __construct() {
PEAR_Exception::addObserver( array( $this, "notifyError") );
}
function process() {
try {
$feedt = new MyFeedThing();
$parser = $feedt->acquire('wrong.xml');
} catch ( Exception $e ) {
print "an error occurred. See log for details\n";
}
}
function notifyError( PEAR_Exception $e ) {
print get_class( $e ).":";
print $e->getMessage()."\n";
$cause = $e->getCause();
if ( is_object( $cause ) ) {
print "[cause] ".get_class( $cause ).":";
print $cause->getMessage()."\n";
} else if ( is_array( $cause ) ) {
foreach( $cause as $sub_e ) {
print "[cause] ".get_class( $sub_e ).":";
print $sub_e->getMessage()."\n";
}
}
print "----------------------\n";
}
}
$client = new MyFeedClient();
$client->process();
All the usual caveats about sample code apply here, of course—especially since this particular
example is designed to fail. First of all, notice the constructor. PEAR_Exception::addObserver() is a static
method that accepts a callback, either a function name or an array containing an object reference and a
method name. The method or function will be invoked every time a PEAR_Exception is thrown. This trick
allows us to design MyFeedClient so that it logs all exceptions.
The process() method passes a nonexistent file to MyFeedThing::acquire(), which passes it on to
the XML_Feed_Parser constructor, thereby guaranteeing an error. We catch the inevitable exception and
print a simple message. notifyError() is the callback method I referenced in the MyFeedClient
constructor. Notice that it expects a PEAR_Exception object. In this case, I simply query the object and
print out error information, although in a real-world situation, I would probably send this data to a log.
Notice the call to PEAR_Exception::getCause(). Because this could return an array or a single Exception
object, I handle both cases. If I run this toy code, this is what I get: