PHP Exceptions and CodeIgniter

I’ve been toying around with PHP’s Exceptions for a number of years now. I never found a clean way to integrate them into my CodeIgniter codebases, until now. I learned about PHP’s SPL Exception library recently as well, so it was a bit of a motivator.

I updated my models and libraries to throw exceptions, rather than my custom error structures. Here is an example model.

class some_model extends CI_Model {
	public function add()
	{
		some_logic();
		if($some_error == TRUE){
			throw new Exception('my exception message',1234);
		}
		more_logic();
		if($some_other_error == TRUE){
			throw new Exception('my 2nd exception message',1234);
		}
		return my_response();
	}
}

Now in my controller, I put:

class MY_Controller extends CI_Controller
{
	public function controller_method()
	{
		$this->load->model('some_model');
		try {
			some_more_logic();
			$expected_response = $this->some_model->add();
			more_logic_assuming_expected_response_is_valid($expected_response);
		} catch (Exception $e) {
			do_behavior_for_exceptions();
		}
	}
}

In my controller method, I wrap the entire controller code in a try/catch loop to catch systematic errors, like database errors, function input validation errors, and other fatal errors. If I have other reasons to throw an exception, then I can add additional try/catch blocks.

Also, because exceptions are classes, you can extend them and perform common logic from within the exception’s constructor when its thrown.

For more information, see the PHP manual, or give us a holler.

Leave a Reply

Your email address will not be published. Required fields are marked *