For Testable & Maintainable Codes
- DRY
- Dependency Injection
- Interfaces
- Containers
- Unit test with PHPUnit
//SiteController.php
/**
* SiteController class file.
*
* @author Winu Sebastian
*/
interface ISite {
public function setClass();
}
class SiteController extends Controller implements ISite{
public function init(){
$this->setClass();//to initialize all objects
}
public function actionIndex(){
$view = new ViewManager($this); // passing object of this controller to get object of interface ISite
$this->render('index', array('leads' => $view->getLead()));
}
public function setClass() {
return new Store();
}
}
//ViewManager.php
interface IView{
public function getLead();
}
class ViewManager extends CComponent implements IView {
public $obj;
public $get;
public function __construct(ILead $ilead) {
$this->obj = $ilead->setClass();
$this->get = $this->obj->get('GLS');
}
public function getLead() {
return $this->get->giveLeads();
}
}
//GetLeads.php
interface IGet {
public function giveLeads();
}
class GetLeads extends CComponent implements IGet {
public function giveLeads(){
return array(
'name'=>'winu',
'email'=>'winu@gmail.com',
'place'=>'Kerala',
'phone'=>'123123'
);
}
}
//Container.php
class Container extends CComponent{
public $classes = [];
public function set($id, $class) {
$this->classes[$id] = $class;
}
public function get($id) {
$reflection = new ReflectionClass($this->classes[$id]);
$instance = $reflection->newInstanceWithoutConstructor();
return $instance;
}
}
//Store.php
class Store extends Container {
public $data = array();
public function __construct() {
$services = array(
'GLS' => 'GetLeads',
'WKM' => 'WorkflowManager',
'VWM' => 'ViewManager'
);
foreach ($services as $key => $value) {
parent::set($key, $value);
}
parent::set('MOD_CLASS_1', 'SampleModel', array(Yii::app()->db));
//Its for model classes, here we can inject db object to the contructor
}
public function __set($key, $value) {
$this->data[$key] = $value;
}
public function __get($key) {
return isset($this->data[$key]) ? $this->data[$key] : NULL;
}
public function __unset($key) {
unset($this->data[$key]);
}
}
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.