Book Image

Learning PHP Data Objects

By : Dennis Popel
Book Image

Learning PHP Data Objects

By: Dennis Popel

Overview of this book

PDO is lighter, faster, and more powerful than existing PHP data abstraction interfaces. PDO is a common interface to different databases that must be used with a database-specific PDO driver to access a particular database server: the PDO extension does not provide a database abstraction by itself; it doesn't rewrite SQL, emulate missing database features, or perform any database functions using by itself. It performs the same role as other classic database abstraction layers such as ODBC and JDBC: it's a query abstraction layer that abstracts the mechanism for accessing a database and manipulating the returned records; each database driver that implements the PDO interface can also expose database-specific features as regular extension functions. ¬ PDO ships with PHP 5.1, and is available as an extension for PHP 5.0; it requires the new object-oriented features of PHP 5, and cannot run with earlier versions of PHP.This book will teach you how to use the PDO, including its advanced features. Readers need to be aware of the basics of data abstraction and should be familiar with PHP.
Table of Contents (13 chapters)

Exceptions


As we have seen, exceptions are a very important addition to PHP5. Exceptions are special kind of object that, when instantiated and thrown, break the normal execution flow and jump to a so called catch block.

Exceptions are used to report error conditions. Traditionally, functions return error codes if they fail. The application has to check every function call before proceeding to the next function call. Remember the piece of code that you use to connect to a MySQL database:

$dbh = mysql_connect($host, $user, $pass);
if(!$dbh) {
die('Could not connect to the DB!');
}
if(!mysql_select_db('mydb')) {
die('Could not select the DB');
}
$q = mysql_query('SELECT * FROM test');
if(!$q) {
die('Could not execute query');
}
while($r = mysql_fetch_row($q))
{
...
}

If the mysql_xxx functions could throw exceptions, this code could be simplified to this:

try
exception handlingexception, throwing{
mysql_connect($host, $user, $pass);
mysql_select_db('mydb');
$q = mysql_query('SELECT * FROM test');
while($r = mysql_fetch_row($q))
{
...
}
}
catch(Exception $e)
{
die(e->getMessage());
}

Of course, this code would not work, as these functions are not designed to throw exceptions. You will have to use PDO, and in Chapter 3 we saw how to work with PDO exceptions.

Exceptions allow you to postpone error checking and maintain cleaner code. A function (or method) that causes an exception to be thrown is terminated, and the code in the block specified by the catch keyword is executed. Any code that might throw an exception is wrapped into the try block:

try
{
// do something exceptional
}
catch(Exception $e)
{
// display warnings etc
// $e->getMessage() contains error message
}

The real power of exceptions is the ability to escalate them up the call stack. This means that, if you design a function or class method that can throw an exception, that function or method does not have to catch that exception. In fact, many application libraries are designed in such a way so that they don't process exceptions themselves, but instead let them pass to the calling code.

For example, many of the methods of the PDO and PDOStatement classes that we have encountered in this book can throw exceptions, and it is your responsibility to catch them and act appropriately.

Take a closer look at the catch block in the above code snippet. It is followed by the word Exception (which is the name of the base class for all exceptions in PHP) and the variable identifier $e. We can use the $e variable inside the catch block to inspect the error message and other debug information. The Exception class defines the following methods:

  • getMessage() returns the error message.

  • getCode() returns the error code.

  • getFile() returns the name of the file where the exception occurred.

  • getLine() returns the number of the line where the exception occurred.

  • getTrace() and getTraceAsString() return the backtrace (call stack), useful for debugging.

Of course, the error messages and error codes vary depending on where the exception occurred, so that they depend on which application library (such as PDO) you use.

We specified the Exception class name after the catch keyword, because this class, like other classes, can be extended to create subclasses. For example, all exceptions that are thrown from PDO methods are instances of the PDOException class.

The exception handling mechanism allows us to create different handling routines for different classes of exception. For example, we can do the following:

try
{
$conn = new PDO('sqlite:./mydb', '', '');
$q = $conn->query('SELECT * FROM test');
while($r = $q->fetch())
{
...
}
}
catch(PDOException $pdoe)
{

die('Database error: ' . $pdoe->getMessage());
}
catch(Exception $e)
{

die('Unexpected error: ' . $e->getMessage());
}

This code defines two error handling routines for all PDO errors: one class for a database error and another class for all other errors, which we identify as unexpected errors. Of course, in real life applications, the error handling strategies would be more complicated, but this example shows how exceptions can be classified.