Home arrow PHP arrow Page 4 - A Custom Exception Class for Dynamic Twitter Signature Images with PHP

Building the custom exception - PHP

Welcome to part four of a five-part series on creating a dynamic Twitter signature image in PHP. In the last segment, I showed you how to implement PHP 5 exceptions as an error-handling mechanism in your signature image application. Today we’re going to expand upon that concept by creating a custom exception class for handling error states in our application.

  1. A Custom Exception Class for Dynamic Twitter Signature Images with PHP
  2. Examining the SignatureImage class
  3. Building a custom exception interface
  4. Building the custom exception
  5. Implementing the custom exception
By: Nilpo
Rating: starstarstarstarstar / 3
August 27, 2009

print this article



We’re going to build a custom exception called SignatureImageException.  Every error in our SignatureImage class will throw this same type of exception.  In larger applications, you’d most likely have a unique exception for each type of error thrown by a particular class.  Due to the small footprint of this application, it’s overkill to have so many different exceptions that will inherently perform the same task.

final class SignatureImageException extends Exception implements ExceptionInterface


We begin building our custom exception class by writing its declaration.  Notice that this exception class will be extending the native Exception class (meaning that it will inherit all of its functionality) and that it also implements the interface we’ve just created.  This provides a level of continuity by ensuring that our class cannot be created without all of the required parts.  I’ve also gone one step farther and declared this as a final class, since our application won’t be extending upon it.

    protected $message = 'Unknown exception';

    protected $code = 0;

The next step is to add the necessary class properties.  These are the same properties used by the native Exception class.  The $message property will contain a text string containing the exception message and the $code property will contain a user-supplied error code as an integer.

    public final function __construct($message = null, $code = 0)


        if (!$message) {

            throw new SignatureImageException('Unknown exception');


        parent::__construct($message, $code);


After defining the properties for our class, we’ll want to override the native Exception class’s constructor with one of our own.  In the native Exception class, all of the constructor’s parameters are optional.  We’re overriding that with a constructor declaration that makes the message and code parameters required.

Next, you’ll see a simple If block.  Here I’m checking that the message parameter contains a usable value.  If it’s null or an empty string, the SignatureImageException is re-thrown with the message “Unknown exception.”  This ensures that the image produced by our custom exception class will always have a visible message for the end-user.

Finally, we make a static call to the Exception class’s constructor.  This ensures that all information is preserved and correctly passed to all parent objects.  It also executes the native code that properly assigns all of the internal properties for our custom exception class.  No need to write the code ourselves!

    public final function getImage()


        if (!function_exists('gd_info')) {

            throw new Exception('No GD support');


        $image = @imagecreatefromjpeg('banners/my_banner.jpg');

        if (!$image) {

            $image = @imagecreate(380, 60);

            if (!$image) {

                throw new Exception('Cannot create image');


            $bg    = imagecolorallocate($image, 190, 240, 250);


        $line    = parent::getMessage();

        $font    = 3;

        $fwidth  = imagefontwidth($font);

        $fheight = imagefontheight($font);

        $color   = imagecolorallocate($image, 100, 100, 100);

        $ttop    = (imagesy($image) - $fheight) / 2;

        $tleft   = (imagesx($image) - ($fwidth*strlen($line))) / 2;

        imagestring($image, $font, $tleft, $ttop, $line, $color);

        header("Content-type: image/jpeg");

        $created = @imagejpeg($image);

        if (!$created) {

            throw new Exception('Unable to finalize image.');





Now we wrap up our custom exception class by creating a method that will produce and output an image containing our error message.  Since the majority of this code has been covered in the previous articles in this series, I won’t go into great detail about its inner workings. 

I do want you to notice, however, the manner that I’ve used to handle errors in this portion of the code.  To this point, our custom exception relies on the fact that it creates and outputs an image.  If this code fails for any reason, the whole concept behind this application fails with it. 

For that reason, any errors produced while attempting to create the image will be thrown as general Exceptions which don’t rely on the need to create an image for the error.  This provides an excellent example of a situation in which a custom exception is better re-thrown as a lower level exception within an application.

>>> More PHP Articles          >>> More By Nilpo

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: