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?
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":
Then just add your interfaces into the "interfaces" folder and you should be able to use them like normal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With