Extending or replacing core classes in CodeIgniter 2x

It has been quite some time that CodeIgniter 2x has been released after a quite long waiting. There are several improvements in this latest release and upgrading from the 1x is quite easy. However, they have changed some file/folder organization in this latest release. I found these changes as good as it provides better application wise personalization. CodeIgniter’s previous file/folder structures were not (at least, by default) very good (without some/little modification) for hosting multiple application based on single core installation. However, in this version they organized it better.

On of the major change was made in this version in replacing and/or extending core classes. There was no note in their upgrade guide (but explains in their relevant doc page, which I found later). So I had to go through little trouble with it until Arafat Rahman helped me out!

However, the process is simple. In version 2x, they have introduced a new directory called ‘core’ (along with few others). All core classes that needs to be replaced or extended should be in this directory. I liked it very much, as I hated to put core classes in library directory in older versions.

Replacing a core class
Let’s say we want to replace a core class by our own version. Also let’s assume we want to replace the model class (actual name is CI_Model). Now follow these steps:

  • Create a directory named ‘core’ in your application directory, if it does not exist. If your application directory is default one, it would be ‘application/core’
  • Create a new file named Model.php.
  • Put the following line in the newly created empty file:
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
class CI_Model
{
 function __construct()
  {
  }
}

Now when you create model classes in current application extend the CI_Model as you were doing earlier, this class will be extended rather than the CI_Model class in the system/core/Model.php. However, when you do, think if you have enough reasons to replace the core class as you can do most, if not all, of the tasks by simply extending it.

Extending the core class

Rather than replacing, I find it much better to extend the core class and use that class in my application. The steps of extending the core class are also simple. Continue reading →