container Dependency Injection in Yii 1.0 using PHP 5 ReflectionClass

For Testable & Maintainable Codes

  1. DRY
  2. Dependency Injection
  3. Interfaces
  4. Containers
  5. 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]);
    }
}
0 0
2 followers
0 downloads
Yii Version: 1.1
License: BSD-2-Clause
Category: Others
Developed by: winu
Created on: Apr 11, 2014
Last updated: 3 years ago

Related Extensions