Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP interfaces in Codeigniter

I am trying to find out how can I used PHP interfaces in my MVC design. I want to make sure that the design enforces an interface so that any new module would follow that.

For example:

<?php

interface BaseAPI {
     public function postMessage($msg);
}

class ServiceAPI implements BaseAPI {
     public function postMessage($msg) { return $msg; }
}

class Service_Two_API implements BaseAPI {
     public function postMessage($msg) { return "can't do this: ".$msg; }
}

?>

I want to do this in CI. Is it possible? how should I design it?

like image 222
Obaid Avatar asked May 16 '10 14:05

Obaid


1 Answers

Here's How to Get CodeIgniter to Load Interfaces Properly

In your application/config/autoload.php:

// Add "interface_autoloader" to your models array
$autoload['model'] = array('interface_autoloader');

Now create a new class in your application/models folder "interface_autoloader.php":

<?php

class Interface_autoloader {

    public function __construct() {
        $this->init_autoloader();
    }

    private function init_autoloader(){
        spl_autoload_register(function($classname){
            if( strpos($classname,'interface') !== false ){
                strtolower($classname);
                require('application/interfaces/'.$classname.'.php');
            }
        });
    }

}

Now create a new folder in your application folder called "interfaces": Example of Interface Usage with CodeIgniter

Then just add your interfaces into the "interfaces" folder and you should be able to use them like normal.

like image 146
Timothy Perez Avatar answered Sep 20 '22 02:09

Timothy Perez