How to Create Custom Drivers in CodeIgniter

Working as a CodeIgniter developer, you might have come across the concept of a library that enriches the core framework functionality, and CodeIgniter itself provides lots of useful libraries in the core. 

Similarly, a driver is a special kind of library that allows you to add custom features so that the main driver class acts as a parent class and the adapters are treated as child classes.

The best way to understand the concept of drivers is to look at how caching is implemented in the core CodeIgniter framework. The main Cache class acts as a parent class and extends the CI_Driver_Library class. On the other hand, you’ll end up finding child classes for APC, Memcached, Redis and the like, implemented as pluggable adapters. The child classes extend the CI_Driver class instead of the main driver class.

The beauty of this approach is that you could easily extend the driver’s functionality by adding a new adapter as needed. As in the case of caching, if you need to add a custom caching strategy, you’re just a step away from implementing it in the form of a custom adapter.

Creating a custom driver in the CodeIgniter application is the aim of today’s article. In the course of that, we’ll go through a real-world example that creates a MediaRenderer driver used to render the media from different services like YouTube, Vimeo and similar. The different services will be implemented in the form of adapter classes.

File Setup

The name of the driver that we’re going to implement in this article is MediaRenderer. Let’s have a quick look at the list of files that are required for the desired setup:

  • application/libraries/MediaRenderer/MediaRendererInterface.php: It’s the interface that the adapter needs to implement.
  • application/config/mediarenderer.php: The configuration file that holds our custom driver related settings.
  • application/libraries/MediaRenderer/MediaRenderer.php: It’s the class that extends the CI_Driver_Library and is used to operate the different adapters available in the application.
  • application/libraries/MediaRenderer/drivers/MediaRenderer_youtube.php: It’s the class that implements the YouTube adapter.
  • application/libraries/MediaRenderer/drivers/MediaRenderer_vimeo.php: It’s the class that implements the Vimeo adapter.
  • application/controllers/Media.php: It’s the controller class that we’ll implement to demonstrate the usage of our custom driver.

So that’s the list of files we’re going to implement throughout this article.

Create Drivers

In this section, we’ll create the base files of our custom driver.

The first thing that we need to do is to define the configuration file of our custom driver. Let’s define the application/config/mediarenderer.php file as shown below.

Powered by WPeMatico

Leave a Comment

Scroll to Top