jigniter™

jQuery & CodeIgniter – Perfect combination for web application

Archive for the ‘constants’ tag

How do I use Constants in CodeIgniter applications?

without comments

Usually I need to use constants or pass them as parameter in a function.

I don’t like the idea to hardcode these values in the code, nor sometimes I don’t like to use the PHP define() function to define constants since later it is a mass to search where a constant for a given entity has been defined.

Recently I started to use constants by defining these constants in a model Class (as reference you can find more info about Object Constants here).

Let’s say we have an Order_model class that manages Orders in an e-commerce application built in CodeIgniter. That Order_model class will implement the methods for create, update, list or view orders, for example.

Now, imagine we want to define simple states for each order. So, an order can be APPROVED as 1 or PENDING as 0.

A natural way to do that (wrong way IMHO) is to set the numeric value (1 or 0 in this case) hardcoded.

Instead of that, I created two object constants, as follows:


class Order_model extends Model {

    var $tablename = 'Orders';
    var $tablename_details = 'OrderDetails';

    const ORDER_STATUS_PENDING = 0;
    const ORDER_STATUS_APPROVED = 1;

Then, imagine we have an update_order_status() function in that model that will change the order status:


function update_order_status($order_id, $new_status)

Later, in the Controller class that will call this update function, I’ll use the constant in this way:


$this->order_model->update_order_status($order_id, Order_Model::ORDER_STATUS_APPROVED);

By doing that, the next time I need to change or maintain that code, I’ll go directly to the model class.

Written byadmin

August 28th, 2009 at 5:19 pm

Posted inSnippets Ideas

Tagged with ,