Django has an excellent function that assists in working with models, get_object_or_404. As Python functions tend to, the name of this function is pretty descriptive: we attempt to get an object (from the model) and if we can’t we throw a 404 error to the user.

We can achieve a rather similar effect, and clean up our code, within a CodeIgniter controller. In the following example, we’ll load a model and attempt to retrieve a record, throwing a 404 error if the request fails:

The other key component to this is the model itself, ensuring a value interpreted as FALSE is returned when an object can not be found. Here’s a quick sample:

NULL (along with FALSE, 0, and an empty string) are all interpreted as FALSE by PHP in a loose comparison (== as opposed to ===). When assigning a value to a variable using the OR operator, PHP will assign the first value that is interpreted as TRUE or the last value within the condition. Since our model will return NULL if a record is not found, PHP attempts to assign the return value of show_404() to that variable. This function doesn’t return a value though, instead it send your application’s ./errors/error_404.php (with appropriate headers) to the user – the exact functionality we desire!

One Response to “Mirror Django’s get_object_or_404 in CodeIgniter”

  1. Kumar Chetan Sharma Says:

    As soon as I read return Null after reading that Model returns false, question popped up in my brain is Null === false, you quickly answered it. :-)
    Anyway, thanks a ton for making my life easy, I can easily throw a 404 page now.

Leave a Reply