Simple way to use custom PHP interfaces within Codeigniter application

Codeigniter itself doesn’t provide any built-in method to use custom PHP interfaces. So if you want to implement some in your class, this requires a little hacky solution.

First create an extension class for Codeigniter loader. This will let you load interfaces using $this->load->iface() method (‘interface’ is a reserved PHP word, so it can’t be used as a function name). File path should be: /application/core/MY_Loader.php

class MY_Loader extends CI_Loader {

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

  public function iface($strInterfaceName) {
    require_once APPPATH . '/interfaces/' . $strInterfaceName . '.php';
  }

}

Now create a new folder for interface files: /application/interfaces. This is an example interface /application/interfaces/CrudModelInterface.php code:

interface CrudModelInterface {
    public function create();
    public function load();
    public function update();
    public function delete();
}

To implement a particular interface in your class just load it right before the class beginning. In this case it’s loaded in model file, so get_instance() finction must be used instead of $this variable.

get_instance()->load->iface('CrudModelInterface'); // interface file name

class User extends CI_Model implements CrudModelInterface {

(...)

Leave a Reply

Your email address will not be published. Required fields are marked *