The New Myth family: SprintPHP Bonfire Practical CodeIgniter 3

New Myth Media Blog

Serving the New Myth Media Family.

Practical CodeIgniter 3 Released

My new book about making the most of CodeIgniter 3 is out in Early Access!

Now that the ribbon has been taken off of the first semi-release of CodeIgniter 4, people are wondering how they get started with it. A couple of things have changed that make a big impact on getting started when you're expecting it to be just like CI3. This article aims to help you out there.

Download It

There are two different ways you can download it currently, but they're both basically the same thing.

  1. From the terminal type: git clone which will pull down the latest version of the develop branch into a new directory called CodeIgniter4.
  2. From GitHub do a straight download by clicking Clone or Download and then selecting Download Zip. Unzip into a new folder when you're done.

Look Around

If you start taking a look around the new code you'll see a slightly different folder layout than you're used to, though the changes are minimal:

/application        - Your app's files go here
/public             - This is the "web root" of your application. index.php is here
/system         - CodeIgniter lives here
/tests              - Holds tests for CodeIgniter and your application
/user_guide_src - The source files for the user guide. Instructions how to build them.
/writable           - A place for any folder that needs to be writable

The two most important right now are the public and the user_guide_src folders. public holds the new web root of the application. Best practices tell us that your application should live outside of the web and not be accessible from a browser. With this layout, only the files in public are available to end-users through the browser. This is in line with every other major framework out there, but is a change from the way that CodeIgniter has always done it.

The user_guide_src folder contains all of the current documentation for the framework. To the best of our knowledge it is completely up to date with the current release, and we plan on keeping it in sync as we go. This will be your best friend, as you explore over the coming days or weeks. While this isn't the generated HTML, all of the files in the source folder inside it are human-readable and laid out similarly to what you're used to in CI3 docs. Take time to read through the new things in here as most of your questions should be answered, and you'll hopefully find some nice surprises lurking in places.

The following pages are good reads to get started with:

Start Playing

In order to start playing around with the new code, you'll need to get it running in a browser. There's a number of ways to do it, but we'll cover two here.

PHP Server

PHP has a built-in web server now. This is the simplest way to get running. Jump to the command line, navigate to the public directory, and type the following:

$ php -S localhost:8000

That's it. Back to your browser, navigate to http://localhost:8000 and you should see the shiny new CI4 welcome page.

Virtual Host

A more permenant solution is to have another web server running locally, like Apache or NGINX, and create a new virtual host for it. This allows you to create a name for the site, like, and use that in your browser. This is especially helpful so that you don't have to worry about RewriteBase commands for Apache config, or any other tricky ways to get past the public folder. When you setup the virtual host, make sure it is pointing to the public folder or it won't work.

Here are some helper guides for those of you using popular AMP stacks locally:

Note that most of these are essentially the same thing, since you're editing raw Apache config files.

Laravel Homestead is another excellent solution for a PHP7 virtual machine running under NGINX.

Lastly, have fun!

It used to be that the majority of the websites were silos, not communicating with other websites much at all. That has changed a lot in the last few years, though, to the point where many sites consume information from external APIs, or communicate with third-party services, like payment gateways, social networks, and more, all on a day-to-day basis. For PHP developers, this typically involves the use of curl to make this happen. That means that any full-stack framework should provide some form of capabilities to help you out there. In the upcoming CodeIgniter 4, we've provided a lightweight, yet still very flexible, HTTP client built-in.

The CURLRequest Class

The CURLRequest class extends our more generic Request class to provide most of the features that you'd need on a day-to-day basis. It is a synchronous-only HTTP client. Its syntax is modeled very closely after the excellent Guzzle HTTP Client. This way if you find that the built-in client doesn't do everything you need it to, it is very easy to switch over to using Guzzle and take advantage of some of its more advanced features, including asynchronous requests, non-reliance on curl, and more.

Why build our own solution? For the last decade, many developers have looked to CodeIgniter as the framework that you can download and have 90% or more of the features you need to build your site at your fingertips. Bundling something like Guzzle into the framework doesn't make sense, when Guzzle provides its own HTTP layer, duplicating a large part of the core system code. If we wanted to provide a solution, we had to build our own, based around our own HTTP layer. Being a lightweight solution, it is primarily a wrapper around curl and so the only real trick was ensuring syntax compatibility with Guzzle to make your transitions, if you need to do them, as simple as possible.

NOTE: This does require that the curl library be installed and usable.

A Few Quick Examples

Let's walk through a few quick examples to see how easy and convenient it is to have a curl wrapper in our bundle of tricks. These examples are obviously very bare-bones and don't provide all of the details you would need in a finished application.

A Single Call

Let's say you have another site that you need to communicate with, and that you only need to grab some information from it once, not as part of a larger conversation with the site. You can very simply grab the information you need something like this:

$client = new \Config\Services::curlrequest();
$issues = $client->request('get', '');

The request() method takes the HTTP verb and URI and returns an instance of CodeIgniter\HTTP\Response ready for you to use.

if ($issues->getStatusCode() == 200)
    echo $issues->getBody();

Consuming an API

If you're working with an API for more than a single call, you can pass the base_uri in as one of a number of available options. Then, all following request URIs are appended to that base_uri.

$client = new \Config\Services::curlrequest(['base_uri' => '']);

// GET

// GET

Submitting A Form

Often, you will need to submit a form to an external site, sometimes even with file attachments. This is easily handled with the class.

$client =  new \Config\Servies::curlrequest();
$response = $client->request('POST', '', [
    'multipart' => [
        'foo' => 'bar',
        'fuz' => ['bar', 'baz'],
        'userfile' => new CURLFile('/path/to/file.txt')

Multitude of Options

The library supports a wide array of options, allowing you to work with nearly any situation you might find yourself up against, including:

  • setting auth values for HTTP Basic or Digest authentication
  • setting arbitrary header values for more complex authentication (or any other needs)
  • specifying the location of PEM-formatted certificates,
  • restricting execution time
  • allowing redirects to be followed,
  • return content even when it encounters an error
  • easily upload JSON content
  • send query string or POST variables with the request
  • specify whether SSL certificates should be validated or not (helpful for development servers who don't have full SSL certificates in place)
  • and more.

Hopefully, this new addition to the framework will come in handy during development and help make using curl much more pleasant.

While work on the database layer is still under heavy construction, I think we're far enough along to be able to give you a glimpse into how it works, how it's the same, and how it's different from what you're accustomed to in previous versions.

First things first: how far along is it? At the moment we can connect to a MySQL database and run both raw queries, and use the Query Builder to run queries. I just wrapped up tests on the existing Query Builder features, I believe, so it should be fairly solid at the moment. What's left? The Query Caching layer needs built, as does the Forge, and the utility methods, as well as getting the drivers in place and in shape.

What's the Same?

While the underlying structure of the database engine has been changed a fair amount, what you'll see while using it will be fairly familiar. The biggest cosmetic difference is in method names using CamelCasing instead of snake_casing. The query builder still largely works like you're used to, so there won't be much to relearn. You should be able to dive right in and use your years of experience with just the tiniest amount of time getting accustomed to it.

What's different?

I won't go into all of the details here, just the big items. Instead of a boring little list, let's take a look at a few examples of it in action.


The config files are still mostly like the old ones. There was no need to reinvent the wheel here since it worked great already. They have been changed to be a simple class, like the rest of them but the fields are the same.

class Database extends \CodeIgniter\Database\Config
     * Lets you choose which connection group to
     * use if no other is specified.
     * @var string
    public $defaultGroup = 'default';

     * The default database connection.
     * @var array
    public $default = [
        'dsn'          => '',
        'hostname'     => 'localhost',
        'username'     => '',
        'password'     => '',
        'database'     => '',
        'dbdriver'     => 'MySQLi',
        'dbprefix'     => '',
        'pconnect'     => false,
        'db_debug'     => (ENVIRONMENT !== 'production'),
        'cache_on'     => false,
        'cachedir'     => '',
        'charset'      => 'utf8',
        'dbcollat'     => 'utf8_general_ci',
        'swapPre'      => '',
        'encrypt'      => false,
        'compress'     => false,
        'stricton'     => false,
        'failover'     => [],
        'saveQueries' => true,



Raw Queries

Making queries without using the Query Builder is simple. Get a database instance, run the query() method and get back a result object.

// Connects to the default connection, 'default' in this example.
$db = Config\Database::connect();

$query = $db->query('SELECT * FROM users');

// Get results as objects.
$results = $query->getResultArray();
// Get results as arrays
$results = $query->getResultObject();
// Get result as custom class instances
$result = $query->getResult('\My\Class');

The first thing to note is that num_rows() has been removed. For the last few years it's use has been discouraged, and written out of examples, since some drivers have horrible performance and/or memory issues when using it. Instead, all result*() methods return empty arrays if no results, while all row*() methods return null.

Parameter binding still exists:

$query = $db->query('SELECT * FROM users WHERE id > ? AND role = ?', [3, 'Admin']);

Parameter binding has gotten a new trick, though, with named parameters, for more readable (and flexible) queries:

$query = $db->query('SELECT * FROM users WHERE id > :id AND role = :role',
    [ 'id'   => 3,
      'role' => Admin'

All values are automatically escaped, of course, to keep your queries safe.

Saved Queries

One of the big changes in the database layer is that all queries are saved in history as Query objects, instead of strings in an array. This is partially to clean up the code and remove some resposibilities from other classes. But it will also allow for more flexibility in the Query Caching layer, and other places. Just be aware that if you need to get $db->getLastQuery() you're getting a Query object back, not a string.

The query objects hold the query string, which can be retrieved with and without the parameters bound to it, as well as any error information that query might have, and performance data (when it started, how long it took).

Query Builder

The Query builder operates mostly as you're used to, with one big change. The Query Builder is now it's own class, not part of the driver files. This helps keep the code cleaner, and works nicely with the new Query objects and named paramater binding, which is used throughout the builder.

One of the biggest benefits of having it as a completely separate class is that it allows us to keep each query completely seperate. There is no more "query bleeding" where you're in the middle of building a query and make a call out to another method to retrieve some values, only to have the other method build it's own query, and incorrectly using the values from the original query. That's a thing of the past.

The primary visible change in the Query Builder is how you access the builder object. Since it's no longer part of the driver, we need a way to get an instance of it that is setup to work with the current driver. That's where the new table() method comes into play.

$db = Config\Database::connect();

$result = $db->table('users')
             ->select('id, role')
             ->where('active', 1)

Basically, the main table is now specified in the table() method instead of the get() method. Everything else works just like you're used to.

What's Still Coming?

Aside from the previously mentioned parts that need implementing, there are some nice additions potentially coming down the pike. There's no guarantee all of these items will make it in, but these are a handful of the ideas I'd currently like to see make it in the database layer.

Native Read/Write Connection Support is likely to make it in the configuration of your database. Once the connections have been defined, using them is automatic. The Connection will determine if your query is a write query or read query and choose the correct connection to use based on that. So, if you have a master/slave setup, this should make things a breeze.

New QueryBuilder Methods will likely be added. I'm going to scout out the other frameworks a little more, to see if there's features that are useful enough to warrant looking into. The following are my short list, though:

  • first() is a convenience method to retrieve the first result itself.
  • increment() and decrement() methods would be nice to have.
  • chunk() would loop over all matching results in chunks of 100 (or whatever). This allows you to process potentially thousands or even millions of rows without completely killing your server or running out of memory.

Enhanced Model The only reason the CI_Model class exists in v3 is to provide easy access to the rest of the framework by using magic methods to access the loaded libraries, etc. That's not really necessary anymore, since there is no singleton object. So, it only makes sense to take this opportunity to actually create a Model class that is useful. The details of this haven't been discussed much in the Council, yet, so I can't say what will make it in. Over the years, though, creating base MY_Model classes with a a fair amount of convenience features has become fairly common. Time to build it into the core, I think.

Simpler Pagination This idea is ripped straight from Laravel, but the first project I worked on in Laravel, it was the pagination that blew me away. This would work hand-in-hand with the Enhanced Model, allowing you to simply call $model->paginate(20) and it would be smart enough to figure out the rest of the details. Obviously, there's more involved than that, but if you've ever used Laravel's version, you'll know how much of a breath of fresh air it is compared to CodeIgniter's. Now, there's is built into their ORM, so it might turn out to be not very feasible for our system, but it's definitely something I want to look into.

I hope that gets you excited about the future of the framework, and maybe calms down some fears that things are going to change too much. One of my big goals while rewriting is to keep the system familiar, while bringing more modern code practices and flexibility into the system.

Are there any features from other systems that you love and miss when you work in CodeIgniter that you'd like us to consider? I won't say that everything (or even any of it) will make its way into the system, but we'll definitely consider it.

One of the big hot-buttons that came up during discussion about CodeIgniter 4 features a few months ago was that of HMVC. It seems that most of the comments fell in one of two uses: either for displaying "widgets" on the page, or for simply splitting code into basically modules. In this article, I wanted to look at how modules can work in the upcoming version of the framework.

NOTE: These examples are all based on pre-release code and the specifics are subject to change at any time.

Module/HMVC Support?

Let me get this out of the way up front: no, CodeIgniter 4 does not support either HMVC, or modules. At least, not in the traditional way that you might think about it. There's no formal definition of module structure, like you might find in a Yii Extension or Drupal plugin. And, there's no hierarchical loading of classes through a nest of different directories.

If that's the case, then how can we support any form of modules? Autoloading and Namespaces.

Autoloading and Namespaces

The framework now ships with a built-in PSR-4 compliant autoloader, no Composer needed (though you're always free to use that in addition to the built-in one).

Why didn't we just use Composer as the core? We talked about it, and I was, at first, a big proponent for it. However, the more we talked and researched, the more it was clear that it wasn't the right thing for the framework. For one thing, it was having an external script at the core of our framework which left us at their mercy. Also, in different hosting environments, Composer can become problematic to update, especially on tightly-secured shared hosting. Finally, since we didn't have to support all of the flexibility and features that Composer does, we could make it a touch faster by default.

Both the system files and your application files can be namespaced. The system files live under the CodeIgniter namespace, while the application directory takes on the App namespace by default. You don't have to namespace your controllers and models if you don't want to. It's entirely optional and things will still work in the way that you're accustomed to working.

When you combine these two techniques, though, 90% of the work of supporting modules is already done for you. Let's look at a quick example, and then we'll cover the remaining 10% of the solution.

A Quick Example

Imagine we are creating a Blog module. The first thing to do is to decide on a namespace and then create a home for all of the files to live. We'll use our company name, Standard, and Blog makes sense for the sub-namespace, since that describes the entire "module". While we could put it anywhere, let's create a new directory alongside the /application directory to hold all of our company's modules. The folder structure might look something like you're used to in HMVC:


Next, open up /application/Config/Autoload.php and let the system know where to find the files. In this example, we'll just create a namespace in the autoloader for the entire company namespace, though you could create additional ones if you want to create one for each module.

$psr4 = [
        'Config'                     => APPPATH.'Config',
        APP_NAMESPACE.'\Controllers' => APPPATH.'Controllers',
        APP_NAMESPACE                => realpath(APPPATH),
        'Standard'                   => APPPATH.'../standard'

Now, as long as we namespace all of our classes, the system can find them and they can be used from anywhere.

namespace Standard\Blog;

use Standard\Blog\Models\BlogModel;
use Standard\Blog\Libraries\BlogLibrary;
use Standard\Blog\Config\Blog as BlogConfig;

class BlogController extends \CodeIgniter\Controller
    public function index()
        $model = new BlogModel();
        $blogLib = new BlogLibrary();
        $config = new BlogConfig();

Simple stuff.

What About Non-Class Files?

If you were paying attention, then you are probably saying, "Sure, buddy, but what about the non-class files, like helpers, and views? huh?!" And you're right. Straight PHP cannot load non-class-based files from namespaces. So, we built that functionality into CodeIgniter.

The way it works is that it will locate the folder based on the namespace of the file, and then look for it in the normal sub-directory. Some examples will clear this up.

Loading Helpers

In our example, we might have a blog_helper file living at /standard/Blog/Helpers/BlogHelper.php. If this were a class, it might have a fully-qualified name like Standard\Blog\Helpers\BlogHelper.php. So we pretend that it is a class, and use the load_helper() function:


And, voila!, it can locate the helper and load it.

Loading Views

When using the module pattern, views can be loaded in the exact same way, except using the load_view() function.

echo load_view('Standard\Blog\Views\index', $data);

The system will also look within the traditional CodeIgniter directories within that namespace so you don't have to include it in the name. The above examples could have also bee done like:

echo load_view('Standard\Blog\index', $data);

While this is not the only way that you can structure things in your application, I hope this gets you excited about the possibilities and flexibility that the framework will be bringing to your applications.

Routes in CodeIgniter have gone through a pretty big upgrade from version 3 to 4. This article will give a 100-foot view of some of the new changes, and give you something to look forward to.

Route Basics

As a refresher, in version 3 routes were specified in a simple array, where each key was the "URI from" and the value of the element was where it should be routed to. It was simple, elegant, worked great, and looked something like this:

$route['join']   = 'home/register';
$route['login']  = 'home/login';
$route['products/(:any)/details'] = 'products/show/$1';

The capability of routers in other frameworks has surpassed the simple elegance we have enjoyed for years. Even in the CodeIgniter community, there have been several router replacements people could use. So, it was time for an upgrade.

The first thing we had to do was to make it use a class, instead of a simple array. We tried to stick with using simple arrays to increase functionality, but it became too much of an complex beast. So, the new routes would look like this:

$routes->add('join',   'Home::register');
$routes->add('login',  'Home::login');
$routes->add('products/(:segment)', 'Products::show/$1');

While the "to" portion of the route looks different, the functionality is much the same here. The join route is being directed to the Home controller, and its register() method. The products route is being directed to the Products controller, with the captured (:segment) being passed to the show() method. While it might appear that the controllers must now use static methods, that is not the case. The familiar syntax was used to specify the controller/method combination only, and methods are not allowed to be static.

Module-like Functionality

Why the new format? Because we don't want to restrict you to controllers in the /application/Controllers directory. Instead, you can now route to any class/method that the system can find through its new PSR-4 compatible autoloader. This makes it a breeze to organize code in module-like directories.

For example, if you have a Blog "module" under the namespace App\Blog, you could create some routes like so:

$routes->add('blog', 'App\Blog\Blog::index');
$routes->add('blog/category/(:segment)', 'App\Blog\Blog::byCategory/$1');

If the Blog controller lives under application/Controllers, great. But if you want to move it into it's own folder, say application/Blog, you can update the autoloader config file and everything still works.


Routes no longer have to mapped to a controller. If you have a simple process you can route to an anonymous function, or Closure, that will be ran in place of any controller.

$routes->add('pages/(:segment)', function($segment)
    if (file_exists(APPPATH.'views/'.$segment.'.php'))
        echo view($segment);
        throw new CodeIgniter\PageNotFoundException($segment);


I'm sure you've noticed a different placeholder than you're used to in the routes: (:segment). This is one of a handful that come stock with CodeIgniter, and is used to replace the (:any) that is in v3 and clear up any confusion. Now, the system recognizes the following placeholders:

  • (:any) will match all characters from that point to the end of the URI. This may include multiple URI segments.
  • (:segment) will match any character except for a forward slash (/) restricting the result to a single segment.
  • (:num) will match any integer.
  • (:alpha) will match any string of alphabetic characters
  • (alphanum) will match any string of alphabetic characters or integers, or any combination of the two.

It doesn't stop there, though. You can create your own at the top of the routes file by assigning a regular expression to it, and then it can be used in any of the routes, making your routes much more readable.

$routes->addPlaceholder('uuid', '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}');
$routes->add('users/(:uuid)', 'Users::show/$1');

HTTP Verbs

So far, I've been using the generic add method to add a new route. Routes added this way will be accessible through any HTTP-verb, whether it's a GET request, POST, PATCH, or even from the command line. It's recommended, though, to restrict the route to only the type of access you need.

$routes->get('products', 'Product::feature');
$routes->post('products', 'Product::feature');
$routes->put('products/(:num)', 'Product::feature');
$routes->delete('products/(:num)', 'Product::feature');
$routes->match(['get', 'post'], 'products/edit/(:num)', 'Product::edit/$1');
$routes->cli('maintenance/on', 'CLITools::maintenanceModeOn');

Generating standard Resource routes

When working on API's it's best to keep a standard set of routes mapping to the same methods in each controller, just to make maintenance simpler. You can can easily do this with the resources method:


This will create the 5 standard routes for a resource:

HTTP Verb Path Action Used for...
GET /photos listAll display a list of photos
GET /photos/{id} show display a specific photo
POST /photos create create a new photo
PUT /photos/{id} update update an existing photo
DELETE /photos/{id} delete deletes an existing photo

The routes can have a fair amount of customization to them through by passing an array of options in as the second parameter, but we'll leave those for the docs.

No More Magic

By default, the URI will attempt to be matched up to a controller/method if no route exists for it. This is very convenient and, for those familiar with it, makes it a breeze to find where the code is that you're trying to use. Sometimes, though, you don't want this functionality.

For example, you might be building an API, and want a single location to serve as documentation for the API. This can be easily handled by turning off the autoRoute feature:


Now, only routes that have been defined can be served up by your application.


Routes can be grouped together under a common prefix, reducing the amount of typing needed and helping to organize the routes.

$routes->group('admin', function($routes) {
    $routes->add('users', 'Admin\Users::index');
    $routes->add('blog',  'Admin\Blog::index');

These routes would now all be available under an 'admin' segment in the URI, like:


Environment Groups

Another form of grouping, environment() allows you to restrict some routes to only work in a specific environment. This can be great for building some tools that only work on develoment machines, but not on the production server.

$routes->environment('development', function($routes)
    $routes->add('builder', 'Tools\Builder::index');

Redirect Old Routes

If your site has some pages that have been moved, you can assign redirect routes that will send a 302 (Temporary) Redirect status and send the user to the correct page.

$routes->addRedirect('users/about', 'users/profile');

This will redirect any routes that match users/about to the new location at users/profile.

Using Routes In Views

One of the more fragile things when building links within views is having your URIs change, which forces you to edit the links throughout your system. CodeIgniter now provides a couple of different tools to help get around this.

Named Routes

Anytime you create a route, a name is made for it. By default, this is the same as the "from" portion of the route definition. However, this doesn't help, so you can assign a custom name to the route. This can then be used with the route_to() function that is always available to return the correct relative URI.

// Create the route
$route->add('auth/login', 'Users::login', ['as' => 'login']);

// Use it in a view
<a href="<?= route_to('login') ?>">Login</a>

Named routes used in this way can also accept parameters:

// The route is defined as:
$routes->add('users/(:id)/gallery(:any)', 'Galleries::showUserGallery/$1/$2', ['as' => 'user_gallery');

// Generate the relative URL to link to user ID 15, gallery 12
// Generates: /users/15/gallery/12
<a href="<?= route_to('user_gallery', 15, 12) ?>">View Gallery</a>

Reverse Routing

For even more fine-grained control, you can use the route_to() function to locate the route that corresponds to the controller/method and parameters that you know won't change.

// The route is defined as:
$routes->add('users/(:id)/gallery(:any)', 'Galleries::showUserGallery/$1/$2');

// Generate the relative URL to link to user ID 15, gallery 12
// Generates: /users/15/gallery/12
<a href="<?= route_to('Galleries::showUserGallery', 15, 12) ?>">View Gallery</a>

Global Options

Any of the route creation methods can be passed an array of options that can help further refine the route, doing things like:

  • assign a namespace to the controllers, reducing typing
  • restrict the route to a specific hostname, or sub-domain
  • offset the matched parameters to ignore one or more (that might have been used for language, version, etc)

Need More? Customize it

If you find that you need something different from the router, it's simple to replace the RouteCollection class with your own, if you want a custom solution. The RouteCollection class is only responsible for reading and parsing the routes, not for doing the actual routing, so everything will still work with your custom solutions.

Just be sure to share what you create with the rest of us! :)

Whew! There's the goodness that you get to look forward to. At least, I think I mentioned it all.