Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 4 ■ EXCEPTIONS^37

set_exception_handler() function to substitute your own logging function that does not
display information.
To use the set_exception_handler() function, you must declare a single function that
takes a single parameter. This function’s name is then passed to set_exception_handler() as a
string. You must, however, declare the function before calling set_exception_handler(), or
you will encounter an error.
Listing 4-5 demonstrates how to use the set_exception_handler() function.

Listing 4-5. Creating a Logging Exception Handler

function exceptionLogger($exception) {
$file = 'var/log/exceptionLog.log';
file_put_contents($file, $exception->__toString(), FILE_APPEND);
}

set_exception_handler('exceptionLogger');

Now, since you have overridden the default exception handler, your uncaught exceptions
are logged and not displayed to the screen.

Exception Overhead


While incredibly powerful, exceptions come at a price. When an exception is thrown in PHP,
many mechanisms must be initialized, including the exception class instances and code back-
traces. If your exceptions log to a file, even more weight is added. The power of exceptions can
make it tempting to overuse them.
You should not use exceptions to control routine application flow, because that would
adversely affect the performance of your application. An example of when not to use an excep-
tion is when searching a database for a login credential and not finding the user. In this case,
you should just return null or false to indicate failure. This is the standard approach of
returning mixed results from a PHP function: valid results to indicate data and false or null to
indicate failure. In other words, when a PHP function fails to locate what it is looking for, it is
common to return null or false instead of that value.

Error Coding


As mentioned earlier, you may want to use error codes to control pragmatic decisions. However, as
your applications get larger, you will want to centralize the strings in the error messages so that
they can be easily updated or even internationalized.
There are literally dozens of ways you can achieve this, but they all share a common quality:
mapping of the error code to a string. You can also create an exception-derived class that will
make operating with coded exceptions easier. Listing 4-6 shows one of the simplest possible
implementations of error coding.

McArthur_819-9C04.fm Page 37 Friday, February 1, 2008 10:25 AM

Free download pdf