Composer and Codeigniter - Part I Replace The Database/Model Layer

Published on by Safeer

I’ve been working on a large Codeigniter project and the need for some – what now are – basics means I’ve outgrown Codeigniter. Don’t get me wrong, Codeigniter has served me well for years but this project has outgrown Codeigniter, sure I could add the features I need by extending classes, but it’s better to migrate away.

So how do you move a large codebase? One that is actively developed on and cannot afford downtime? Or a change in development pace? The best way is to move is in small steps, so in this article I’ll be showing how to move the Database/Model layer.

For this article we’ll be looking at using the Laravel 4/Illuminate components as Laravel shares alot of the simplicity of Codeigniter with the power of Symfony(Laravel 4/Illuminate Components rely on a fair few Symfony components).

So how do you do it?

  1. Start by jumping into your Codeigniter folder, or download a fresh copy(the latest at time of writing is Codeigniter 2.1.3) as I have for this article. Then set it up as you would normally.

  2. Install composer if you haven’t already, full instructions can be found here. Then set it up for Codeigniter, there’s an article explaining how to do it by Phil Sturgeon over here. Basically it’s adding an include to the composer autoloader to the bottom of index.php.

  3. Once composer is setup, it’s time to create a src directory somewhere, for this article I’ll be putting it in the root of the Codeigniter folder. Though it can be anywhere as long as it’s accessible. Within the src directory create another directory to house your code, this can be called anything but it’s probably best to avoid common names and try to keep it succinct as it may end up being used a fair amount depending on how you structure your app. Finally create a folder called Models in this directory, you should now have a structure like:

src/FooExample/Models
  1. Now it’s time to grab illuminate/database and dhorrigan/capsule. The latter is a simple library that will help configure our database, it’s not strictly needed but the alternative means you’re more or less writing code to do what it does. To get both of these libraries, add the following under require to you composer.json:
"dhorrigan/capsule": "2.*"

and the following in autoload under psr-0:

"FooExample": "src/"

remember to replace FooExample with the name of your folder. If you don’t have the composer.json file, create it in the root directory of Codeigniter and add:

{
    "require": {
        "dhorrigan/capsule": "2.*"
    },
    "autoload": {
        "psr-0": { 
            "FooExample": "src/"
        }
    }
}

Once this above settings have been added to composer.json run the following command in whatever folder your composer.json file is:

php composer.phar update

Composer will go ahead and pull in the illuminate/database library and the dhorrigan/capsule library. In addition to this it will add mappings for your source files.

  1. Now let’s start coding, we’ll be creating a simple Model that let’s someone retrieve, store, update and delete settings from a Database. To do so create a new Model in src/YourNameSpace/Models like:
<?php 

namespace FooExample\Models;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model {
    protected $table = 'settings';
    public $timestamps = false;
}
  1. Then create this library in application/libraries
<?php 

class database_connector {

    function __construct()
    {
        include APPPATH . 'config/database.php';

        \Capsule\Database\Connection::make('default', array(
            'driver'    => $db[$active_group]['dbdriver'],
            'host'      => $db[$active_group]['hostname'],
            'database'  => $db[$active_group]['database'],
            'username'  => $db[$active_group]['username'],
            'password'  => $db[$active_group]['password'],
            'collation' => $db[$active_group]['dbcollat'],
            'prefix'    => $db[$active_group]['dbprefix']
        ), true);
    }

}

then add database_connector to the Codeigniter autoload.php found in config directory. This will ensure the database is always loaded and configured, you could always lazy load it by running

$this->load->library('database_connector');

before calling any Model(s), but having it autoloaded is helpful in most apps.

  1. Then setup the following table in your database:
CREATE TABLE  `settings` (
    `id` INT NOT NULL AUTO_INCREMENT ,
    `name` VARCHAR( 255 ) NOT NULL ,
    `value` VARCHAR( 255 ) NOT NULL ,
    PRIMARY KEY (  `id` )
) ENGINE = INNODB;

remember this is a simple article to illustrate the way to use illuminate/database from Codeingiter and to start moving away from Codeigniter.

  1. Drop the following controller into the Codeigniter controllers and load the page for some magic. This will create entries in the Database and then dump them out again. It relies on the Eloquent Model for the CRUD functionality. This is a really basic example showing how to use Illuminate/Database in Codeigniter, for more information on Eloquent and the Illuminate/Database see here.
<?php

class Settings extends CI_Controller {

    public function index()
    {
        // Insert some records
        $setting = new FooExample\Models\Setting();
        $setting->name = 'Test Setting One';
        $setting->value = 'Created One';
        $setting->save();

        $setting = new FooExample\Models\Setting();
        $setting->name = 'Test Setting Two';
        $setting->value = 'Created Two';
        $setting->save();

        $setting = new FooExample\Models\Setting();
        $setting->name = 'Test Setting Three';
        $setting->value = 'Created Three';
        $setting->save();

        // Retrieve the record with the ID 1
        $setting = FooExample\Models\Setting::find(1);
        var_dump($setting->toArray());
        echo '<hr>';

        // Retrieve all records
        $settings = FooExample\Models\Setting::all();
        var_dump($settings->toArray());
        echo '<hr>';
    }
}

That’s all, let me know if the guide didn’t work for you and I’ll help the best I can. Or tell me I done it wrong with how to do it better… You can download this entire source code by clicking here or by viewing it online at Github over here.