Reducing Startup Time on new codeIgniter projects

In: Development | No Comments
Tags: , ,
By: Ross
Date: 06 April 2010 10:00 am

Reduce Time on Project Startup in CodeIgniter

Whilst thinking of what I could post with the introduction of the Flint blog, I asked myself, why not share some stuff I’ve learnt with my fellow developers? I don’t profess to being the worlds greatest developer, or even a CodeIgniter expert, so please, if you have any recommendations or suggestions, please make them respectable.

Also, this is my first blog post EVER, so take it with a grain of salt. I also use the Yii and CakePHP frameworks, and will cover them in time. Note that this article is aimed at beginners.

As you all know, starting a project in a framework (in this case CodeIgniter) can often be a bit tiresome, as you usually have to take precious time out of your day to configure the project, set up all your models and controllers, as well as to lay out your basic routes and templates. This can be extremely frustrating as it takes anywhere between an hour to a few before you can start the creative coding process (that is, making it work as efficiently and effectively as possible).

I started noticing over the last few projects that alot of the code I was writing was extremely similar, and thus, I wasted the time it took to write it, as I simply could have taken it from a previous project and altered it where necessary. Therefore I’ve started taking notice of what I can reuse, and made some changes to CodeIgniter so that I can share functionality among different classes as often as possible to start projects in less time.

This code is from a recent project, and its not a very complex site in itself, so the functionality isn’t mind-blowing, but I’m just using it as an example of how I try to keep redundancy to a minimum.

Controller Extending

I always take advantage of CodeIgniter’s built-in ability to extend Controllers from a custom one. To do this I create a MY_Controller.php file and create one or more Controller templates that I can extend with my other Controllers.

The usefulness of doing this is that I can share authentication functionality, database querying code (such as if the navigation has items that are dynamic and are therefore stored in the database), and session saving (for cases where you need to save user browsing history and so on so that you can redirect, provide accurate back links, or even allow for session monitoring in the admin section). Of course there are other useful ways in which template controllers can help, but the aforementioned are the most common for me personally.

Find an example of a basic Controller template below. Please note that this would be saved as MY_Controller.php file in the libraries folder of your application:

class MY_Controller extends Controller
{
    function MY_Controller()
    {
        parent::Controller();
        $this->MUser->save_page_view();
    }   

    /* Uses the MUser model to check if the user has been logged in.
    I try to keep extreme session handling in the model as I
    personally feel thats where it belongs, regardless of whether its
    done with the database, cookies, or normal PHP sessions. */

    function _check_auth()
    {
        if(!$this->MUser->isLoggedIn())
        {
            $this->session->set_flashdata('error', 'Please log in first.');
            redirect('users/login');
            exit;
        }
        else
        {
            return true;
        }
    }

    /*I use this to get my navigation items*/

    function _get_sections()
    {
        $this->load->model('MSection');
        return $this->MSection->getList();
    }
}

/* If you wish to create more than one Controller template, this is how you do it.
All Controllers have to go into this MY_Controller file, so it may get long.
You can also extend other controllers defined in the file instead of just the basic
Controller class */

class Another_Controller extends Controller
{
    function Another_Controller()
    {
        parent::Controller();
    }
}

The code above is self-explanatory, but I just show how you can use it to do the basic functions I mentioned earlier. For the saving of pages viewed to the Session, I more often that not use a Hook, but I’ll mention that in a future blog post. I just wanted show that it can be done in the Controller as well.

Model Extending

Similar to the way I extended my Controller above, I do the same for Models. I tend to do this to create basic record management functions that are often the same regardless of the table they are being done on (especially for less advanced sites).

Find the code below. Please note that it would be saved to the MY_Model.php file in the libraries folder of your application:

/* Functions used commonly amongst most basic tables and site sections */

class MY_Model extends Model
{
    var $table_name = '';

    function MY_Model()
    {
        parent::Model();
    }     

    function add($record)
    {
        if($this->db->insert($this->table_name, $record))
        {
            return $this->db->insert_id();
        }
        return false;
    }

    function delete($id)
    {
        $this->db->limit(1);
        $this->db->where('id', $id);
        $this->db->delete($this->table_name);
        return $this->db->affected_rows();
    }       

    function get($id)
    {
        $this->db->where('id', $id);
        $this->db->limit(1);
        $rows = $this->db->get($this->table_name);
        return $rows->row_array();
    }

    function countAll()
    {
        return $this->db->count_all_results($this->table_name);
    }

    function update($id, $record)
    {
        $this->db->where('id', $id);
        $this->db->limit(1);
        $this->db->update($this->table_name, $record);
        return $this->db->affected_rows();
    }
}

To alter the functionality of a method, I just redefine it in the table model itself.

Routes

Routes aren’t something I’m extremently well versed in configuring (I have always been hesitant to use regex, despite its usefulness), but I try to prevent having too many of them as a) it has a drastic effect on performance and b) changing the site at a later stage will be much more difficult if there are 15 routes to remember to change for each section :).

As an example, see the below code from the routes.php file in the config directory:

/* Allowing for dynamic section detection in the case of having many subsites. */

$route['(:num)/(:any)'] = "sections/home/$1";
$route['(:num)/(:any)/contact'] = "sections/contact/$1";
$route['(:num)/(:any)/request'] = "sections/request/$1";

In this case, I could also have just made a pages function and routed all pages through it, instead of having a function for each page type. I decided to keep them separate, however, as there was functionality on some of the pages that made them more complex than would be normal for basic pages.

Views

It all comes down to how diverse and easy to manipulate your Website template is, but wherever possible I try to focus on making different versions of a form, or small piece of code, than creating a whole new template for each small difference.

For example:

Instead of just creating a new main view file and recreating all the markup along with the necessary changes to the template,
such as if you need a different navigation on a certain page, create a separate view file just for the navigation, and depending
on the page being viewed, display the appropriate navigation in the same main view file or template.

if($page == 'showcase'):
    $this->load->view('showcase_nav');
else:
    $this->load->view('normal_nav');
endif;

As obvious as this all sounds, alot of people simply forget to do it, or are just too lazy to plan ahead (I know from experience, after looking at my own old code to perform a content update and eventually losing hair after trying to edit multiple instances of the same code).

Hope It Helps

Well thats all for now. I hope some less experienced CodeIgniter users can find the article helpful.

Related Posts

Leave a comment Name

Follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

No Comments Up Down

Want a custom image by your comment? We use Gravatar [ Free & Quick ]