Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^190) CHAPTER 13 ■ SPL EXCEPTIONS
public function getName() {
if(!$this->_loaded) {
throw new LogicException('Call materialize() before accessing');
}
return $this->_name;
}
}
$lazy = new Lazy();
echo $lazy->getName();
Fatal error: Uncaught exception 'LogicException' with message
'Call materialize() before accessing' in listing1.php:14
Stack trace:
#0 listing1.php(21): Lazy->getName()
#1 {main}
thrown in listing1.php on line 14
Listing 13-1 is an example of a logical exception because it is caused entirely by bad
programming (calling getName() before materialize()), rather than the result of runtime data.
Catching logic exceptions is very easy and also very useful. If your application has a central
dispatch point—and I generally recommend this design pattern—then this can be implemented
application-wide. You could also use the set_exception_handler() function from within each
script if you do not use a central dispatch architecture.
■Note Central dispatch architecture is utilized by the Zend Framework, which is covered in Part 4 of
this book.
Listing 13-2 shows a convenient method of catching LogicException exceptions and
recording their details to a log file using the SplFileObject class (introduced in Chapter 11).
Listing 13-2. Logging Logic Exceptions (Central Dispatch Architecture)
$logfile = 'log.txt';
try {
throw new LogicException("Demo");
} catch (LogicException $le) {
$file = new SplFileObject($logfile,'a+');
$file->fwrite($le->__toString());
}
The SplFileObject instance is created, and the open mode is a+ (append mode), creating
the file if necessary and placing the file pointer at the end of the file. You can then fwrite() to
McArthur_819-9C13.fm Page 190 Thursday, February 28, 2008 7:53 AM

Free download pdf