CodeIgniter 4 (pre-alpha), a complete new ballgame

CodeIgniter 4 (pre-alpha), a complete new ballgame

CodeIgniter 4 is in a pre-alpha stage available. BCIT decided to clean the ship, no.. to rebuild the ship. The new CodeIgniter 4 will be totally redesigned.

Very excited that CodeIgniter 4 is in the make

I was very excited to hear that work in progress is going on on CodeIgniter 4. I've been working with CodeIgniter since version 1.73 and even if I have looked at other frameworks lately. I am a great fan of the CodeIgniter PHP framework that original came from Ellislab, but is now under the hood of British Columbia Institute of Technology. The framework suffered lately from critics that it was not maintained to the latest PHP developments, had no namespace ability, was not HMVC and a bit more. In fact many were referring to other PHP frameworks as the place to go for like Laravel or Symphony. We stayed because most of our customers have software based on a CodeIgniter server back-end.

CodeIgniter 4 (pre-alpha) is not CodeIgniter 3

Since BCIT took CodeIgniter under their protection the train got in motion again. CodeIgniter version 3 saw the light and was very much compatible with version 2. In fact by changing a capital here and there you could migrate an application in a "jiffy". Recently CodeIgniter 4 has been opened to the public in a pre-alpha version. We took a look on how far it is. It is loosely planned to be in a production version available round April 2017.

Well, the first thing I noticed is that it has quite some changes. In fact, at first glimpse, it doesn't look like CodeIgniter as we are used too. BCIT decided to clean the ship, no.. to rebuild the ship. Because the documentation is as virgin as the developments itself, it took me a while to figure out how everything fits on the new ship called CodeIgniter 4, which will only run starting with PHP version 7. So first figure out if your host provider supports or if it is installed and running on your own local server. CodeIgniter 4 is NOT backward compatible with CodeIgniter 3.

Everything is now relating to namespaces. No more $this->load->model('something') but instead you have to get familiar with the "use" and back slashed references of namespaces.

What stayed and what is gone

In this small and not complete review, I will not talk about the "views", because I haven't got that far yet and I am using CodeIgniter mainly as a REST server to Ext JS based applications. I will talk about the "views" in a later article as I will follow the developments of CodeIgniter version 4.

CodeIgniter is still an MVC (model-view-controller) framework and the development team is very clear about HMVC (hierarchical-model-view-controller), it will not be implemented. HMVC is a collection of traditional MVC triads operating as one application. Each triad is completely independent and can execute without the presence of any other.

What you will notice immediately is the different path structure. You will now find an "application", "system" and a "public" path. That needs some explanation. The idea behind all this is that the "public" path should be the root path of your web application. This means that the "system" and "application" would be hidden from the public eye. This is improving security. Also behind the public eye is a "writeable" folder, which has write access, but is not directly accessible by an URL.

No differences in object loading

CodeIgniter is treating the loading of Models, Libraries and other objects in an equal way. Auto-loading of Models or Libraries, as well as other objects, can be set in the "Autoload.php" in the "config" folder. There you have in the constructor a $psr4 array and a $classmap array, which can be used to auto load objects. There is no difference between classes when it comes to auto loading. You have to tell what the namespace is and where it can be found.

$classmap = [
   'TMDB_API' => APPPATH . 'ThirdParty/tmdb-v3.php'
];

This sample shows how a namespace alias is created for a non-CodeIgniter object in the "ThirdParty" folder within the "application" folder.

Loading Models and Libraries in a controller

The excerpt below (of a working application) shows how you load models and libraries in a controller.

The sample has a model class named "TmdbModel" and a library class named "Tmdb". Notice the "use" declarations. You have to get used to it (I did), but you'll get used to it quickly. I had to declare the "CodeIgniter\HTTP\" interfaces for I got an error on the parent construct when I didn't add the $request and $response variables. Simply leaving the parameters out didn't work.

<?php
namespace App\Controllers;

use App\Models\TmdbModel;
use App\Libraries\Tmdb;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class Movies extends \CodeIgniter\Controller
{
    protected $tmdbModel;
    protected $tmdb;

    public function __construct(RequestInterface $request, ResponseInterface $response)
    {
        parent::__construct($request, $response);

        $this->tmdbModel = new TmdbModel();
        $this->tmdb = new Tmdb();

        helper('download');

    }

    ... more code

As you can see the model class and the library classes are declared as new objects. You don't use $this->load->model and $this->load->library anymore, which in fact also created the objects.

The last line of code in the sample above is helper('download'). This is a way to load a helper. Here I have the "download" helper, which I copied from CodeIgniter 3 core into my application "helpers" folder. It didn't complain. In the final version, I expect that many of the core helpers of version 3 will be part of the core of version 4.

Database and input

The database class has been modified somewhat. Some functions are gone and some have now a different method (but maybe not everything is implemented yet).

  • $query->num_rows() is gone, you can use:

count($query->getResult())

  • $query->firstRow() is gone, you can use:

$row = $query->getRow(0);

  • $this->db->insert('table', $record) has changed to:

$this->db->table('table')->insert($record);

  • Post variables:

$search = $this->input->post('search');

becomes:

$search = $this->request->getPost('search');

Libraries as interface to none CodeIgniter classes

I use library classes a lot as an interface to third-party packages or classes like TCPDF (PDF creation) or PHPExcel (Excel creation). I put the contents of such a third-party package in a "third party" folder (like now "ThirdParty") and create a CodeIgniter library class that extends the third party main class. In my TMDB application, I have something like that too. I have a library named "Tmdb" and in the ThirdParty folder, I have a PHP script "tmdb-v3.php" that has nothing to do with CodeIgniter and contains a class with the TMDB API calls. The sample below shows how it I did it in CodeIgniter 4.

In the Libraries folder: Tmdb.php

<?php

namespace App\Libraries;

use TMDB_API; // relates to the Autoload.php config

class Tmdb extends TMDB_API {

    private $API_Key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    private $defaultFormat = self::JSON;
    private $defaultLang = 'en';

    function __construct() {
        parent::__construct(
                $this->API_Key, 
                $this->defaultFormat, 
                $this->defaultLang
        );
    }
}

TMDB_API reference in Autoload.php in the "config" folder (important !!!)

public function __construct()
    {
        parent::__construct();

        ....

        $classmap = [
            'TMDB_API' => APPPATH . 'ThirdParty/tmdb-v3.php'
        ];

        ....
    }
    ...
}

Usage in a model (TmdbModel.php)

<?php

namespace App\Models;

use App\Libraries\Tmdb;  // Library Tmdb

class TmdbModel extends \CodeIgniter\Model
{
    protected $tmdb; // Library Tmdb goes here

    function __construct()
    {
        parent::__construct();

        $this->tmdb = new Tmdb(); // declare Tmdb as a new object
    }

    ...

    function getTopRated() {
        return $this->tmdb->TvTopRated(); // usage of library function
    }

    ...

    function AddBoxoffice($info = array())
    {
        $record = array(
            'id'           => $info['id'],
            'name'         => $info['name'],
            'popularity'   => $info['popularity']
        );

        $this->db->table('tmdb_boxoffice')->insert('tmdb_boxoffice', $record);
    }

    ...
}

KINT, var_dump on steroids

I am very excited about the integration of KINT into CodeIgniter. This service gives an easy way to dump variables in a stunning way. You simply activate by changing the index.php in the public folder.

$useKint = true;

After that it is activated, you can simply use the "d" (dump) and "dd" (dump-die) function to dump your variables.

The result looks like this:

INT, var_dump on steriods

Development, Testing and Production

CodeIgniter gives the possibility to set your environment. You can do that by changing your .htaccess file. You can use "development", "testing" or "production".

# Sets the environment that CodeIgniter runs under.
SetEnv CI_ENV development

With this parameter set, it will use the corresponding boot from the application/config/boot folder.

The toolbar is enabled by default in any environment except "production". It will be shown whenever the constant CI_DEBUG is defined and its value is positive.

It is possible that this feature would not survive the final version. That would be a pitty because it is showing useful information. Maybe it should be optional with another constant like CI_DEBUG_TBAR.

Github and Documentation

You can get the CodeIgniter 4 (pre-alpha) from Github: link.

Creating documentation on Windows systems

It was a bit of a puzzle to get the documentation from the Github repository converted to HTML format. In the folder: "user_guide_src" in the Github repository you will find the instruction on how to install the documentation, which is by default not in HTML format. Below I have added some extra instructions for Windows users. After you have executed these steps you can follow the instructions in the instructions in the Github repository.

Replace with the drive identifier where you have installed Python f.e. "c:".

  • Install Python (2.7.2) from http://python.org/download/releases/2.7.2/
  • After installing Python you will find easy_install executable in directory: :\Python27\scripts
  • You can get the executablemake by installing MinGW from . The easiest way is to install the graphical installer and then after it is installed and started the MinGW installation manager, select only the packagemsys-base. With the menu option: Installation->Apply changes you can install the required files.
  • Make sure you have the following in your path before doing the make html:
    • drive$:\Python27
    • drive$:\Python27\scripts
    • drive$:\MinGW\msys\1.0\bin
  • After modifying the path in your environment variables, close the DOS box and reopen it, your modified path is now applied. Now follow the instructions in the Github repository on how to do the make.

The easiest way to get the generated documentation in your browser is by creating a "user_guide" folder in the "public" folder and to copy the "html" folder from the "build" folder into that folder. You can then open it with: http:///user\_guide.

Where will CodeIgniter bring us and itself?

I am very excited after the first glimpse at CodeIgniter 4. Will it convince current CodeIgniter developers to make the jump to a completely redesigned PHP framework? Or will existing developers look for comparable frameworks? To me it looks very promising because in one aspect it is still very much CodeIgniter, it doesn't have a lot of extra's that makes it all complex to implement.

I just want to say to all CodeIgniter developers out there, stay tuned into CodeIgniter and see what the coming updates will bring and maybe even better; give it a try, it's worth it.

One article is not enough to tell everything that is coming with the new CodeIgniter, but let's say it's a start. I am very excited. I will publish some more articles on the progression I make and share the experience in developing with this exciting soon to be revamped framework. In the following article, I will tell more about my experience in migrating an existing Ext JS application that is using CodeIgniter as a back-end server.

Links

More from same category