Codeigniter design patterns Codeigniter design patterns php php

Codeigniter design patterns


Yes, Codeigniter's loader currently follows the singleton pattern, or at least that's the pattern that most accurately describes it. When you execute the following:

$this->load->library('foo');$this->load->model('foo');$this->load->database('foo');

The loader does the following things:

  • Check to see if the class you're loading has been loaded previously by checking a registry of loaded classes. Silently ignore the request with a debug log entry if it has been loaded.

  • Instantiate the class with whatever parameters you set, create a reference to that object within the framework (singleton-ish) super object named after the class, or whatever custom name you pass. Store the reference, ignore subsequent attempts to load.

On bootstrap, the magic functions in the global scope behind the loader methods are used to construct the DB, core libraries, etc.

A more traditional singleton approach would do something like this (with auto loading):

return $className::instance();

... Where the instance method would return an instance, or construct if not yet instantiated, thus obviating any need to keep track of what has or has not been loaded. If the class has been loaded, a reference would be passed, otherwise a new object would be created and returned.

I suppose technically, CI is its own pattern in this regard, but close enough to a singleton that the term does accurately apply. It really is a singleton, just not implemented in a typical way.

At last I checked there were patches floating around for CI-3 that makes the loader much more flexible, allowing one to work outside of the super object as they please by returning an object or reference in these cases, but I don't know the status of Ellis Labs taking them.