PHP4 Exceptions

During the last project I worked on, before moving companies, I would often want to pass back more error information from methods than primitive types would allow. What I wanted was a PHP4 exception. You’ll need PHP 4.3.0 or above for this class to work.

N.B.: Where you see a back slash (\) I’ve put a line break for code formatting purposes, although this new line doesn’t occur in the code.

class Error {

    var $message;
    var $code;
    var $file;
    var $line;
    var $trace;

    function Error($message = null, $code = 0) {

        $this->message  = $message;
        $this->code     = $code;
        $this->trace    = (phpversion() >= 4.3) \
                          ? debug_backtrace() : array();

    }

    function getMessage() {

        return $this->message;

    }

    function getCode() {

        return $this->code;

    }

    function getFile() {

        return $this->trace['file'];

    }

    function getLine() {

        return $this->trace['line'];

    }

    function getTrace() {

        reset($this->trace);
        return current($this->trace);

    }

    function getArgs() {

        reset($this->trace);
        $trace = current($this->trace);
        return $trace['args'];

    }

}

I then created the following function to identify when the Error class was returned:

function isError($result) {

    return (is_a($result,'Error') ? true : false);

}

I would then use it like so:

class OrderDB {

    ...

    function save() {

        if (!$this->db->query( \
            'UPDATE orders SET ... WHERE order_id = '. \
            $this->order->getId())) {
            return new Error( \
            'Failed to update order '.$this->order->getId());
        } else {
            return true;
        }

    }

    ...

}

Mimicking a try catch block:

$saveResult = $orderDb->save();

if ($saveResult) {
    ...
} else if (isError($saveResult)) {
    $logger = $this->locator->get('log');
    $logger->log('Error occured in '. \
        $saveResult->getFile().' on line '. \
        $saveResult->getLine().': '.$saveResult->getMessage());
    ...
}

An obvious short coming of this solution is that every result must be checked whereas a true try catch statement will catch any exception thrown within the try block. On the plus side you can still extend the Error class and isError will recognise you’ve returned a child of the Error class.

Typically 2 minutes Googling reveals a beefed up PHP4 exception class.

Comments are closed.

Categories

My Bookshelf

PHP in Action: Modern software practices for PHP Agile Web Development with Rails
xhtml 1.1 compliant   xhtml 1.1 compliant