Using Composer with CodeIgniter

3357
Share:
using-composer-with-codeigniter

Background

All web app developers, who have started using modern frameworks like Symfony, Slim, Laravel etc and have wished for the composer support inside their CodeIgniter application, I will try to show you the most efficient and standardized way to achieve this goal. If you are concerned to get support for composer with codeigniter in an existing application, you can totally do that without much worry as well.

Starting from 2015, I never created new PHP project using CodeIgniter. The choice is three:

  1. Plain PHP - For really simple application.
  2. Slim Framework - Simple application with expansion possibility.
  3. Laravel Framework - Application with many dependencies and API integrations.

So, why am I sharing about this? I've developed PHP applications since 2005, so there are possibilities I have returning clients. As most of my past PHP applications were CodeIgniter based and most of my returning clients asked for extra feature, I really need composer support in CodeIgniter.

Composer Logo

Solution

Step 1

If you haven’t yet, install composer on your system first. You can get detailed instruction on official composer getting started documentation.

Step 2

On your application folder, run:

composer require <package-you-wish-to-add>

and wait for installation finished. Then you should notice composer creating a vendor folder in your application and code will be installed there. Composer will also create composer.json and composer.lock in your application folder.

Step 3

Create a file called My_composer.php in application/libraries folder

<?php
/**
 * Description of My_composer
 *
 * @author Adjie
 */
class My_composer
{
    function __construct()
    {
        include("./application/vendor/autoload.php");
    }
}

Step 4

Open autoload.php in application/config folder and add our newly created library My_composer in the autoloaded libraries list. Sample code:

$autoload['libraries'] = array('My_composer','database','session');

Done

It is as simple as that, and here we are done as well. Great!

Final Words

If you are not familiar with Composer or PSR-0 support then you should really look into it. The PHP Standards group or PHP-FIG are doing a brilliant job of taming the mess that is third-party PHP code and are building some great standards, which are open to discussion and voted on by some of the best PHP developers around.

Get involved and help PSR-1 and PSR-2 become something brilliant. In the mean-time enjoy all the PSR-0 code and use it wherever the hell you develop.

 

Tags
Share:

0 comment

Leave a reply

Your email address will not be published. Required fields are marked *