To begin piecing together a custom exception, you’ll first need to understand how the native Exception class is constructed. For that you’ll need to sit down and examine the PHP documentation, so I’ll save you a little time. interface ExceptionInterface { public function __construct($message = null, $code = 0);
public function getMessage(); // message of exception public function getCode(); // code of exception public function getFile(); // source filename public function getLine(); // source line public function getTrace(); // an array of the backtrace() public function getTraceAsString(); // formatted string of trace
public function __toString(); // formatted string for display } In the code above I’ve created an interface that lists all of the methods provided by the native Exception class. By implementing this interface in our own custom exception class, we’ll have a framework to ensure that our own exception is constructed in the same manner as the original. In larger applications, this allows multiple developers to implement any custom exception without the need for additional documentation. That’s an important time-saver any time you have more than one developer collaborating on a project. Now that we’ve got an interface to define our custom exceptions, we can begin putting the code together to make it work.
blog comments powered by Disqus |