Drivers in CI

Why I Copy other People’s Writings


Generally speaking, all the OOP discussions in the User’s Guide so far only deal with libraries in some form or other. A library in CI is a specific type of OOP class which gets loaded once—creating only one instance of that class—after that no other instances of that class get created. Thus, after a library is loaded we end up with just an extra set of related functions; and, some variables which record the “state of the library“.


Basically, drivers in CodeIgniter are like libraries. The difference is that they are made up of a bunch of related classes—and, they get stored and loaded differently.

Using CodeIgniter Drivers

Drivers are a special type of Library that has a parent class and any number of potential child classes. Child classes have access to the parent class, but not their siblings. Drivers provide an elegant syntax in your controllers for libraries that benefit from or require being broken down into discrete classes.

Drivers are found in the system/libraries folder, in their own folder which is identically named to the parent library class. Also inside that folder is a subfolder named drivers, which contains all of the possible child class files.

To use a driver you will initialize it within a controller using the following initialization function:

$this->load->driver('class name');

Where class name is the name of the driver class you want to invoke. For example, to load a driver named “Some Parent” you would do this:

$this->load->driver('some_parent');

Methods of that class can then be invoked with:

$this->some_parent->some_method();

The child classes, the drivers themselves, can then be called directly through the parent class, without initializing them:

$this->some_parent->child_one->some_method();
$this->some_parent->child_two->another_method();

Creating Your Own Drivers

This section is also titled Creating Drivers.

Driver Directory and File Structure

  • /application/libraries/Driver_name
    • Driver_name.php
    • drivers
      • Driver_name_subclass_1.php
      • Driver_name_subclass_2.php
      • Driver_name_subclass_3.php

Note:
In order to maintain compatibility on case-sensitive file systems, the Driver_name directory must be ucfirst().

Advertisements

About samehramzylabib

See About on https://samehramzylabib.wordpress.com
This entry was posted in CodeIgniter. Bookmark the permalink.

Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s