基类和派生类中的依赖注入

时间:2012-02-17 07:11:21

标签: php dependency-injection base-class

我有一个抽象的基本Controller类,所有动作控制器都是从它派生的。

构造中的基础控制器类初始化View对象。所有操作控制器都使用此View对象。每个动作控制器都有不同的依赖关系(这可以通过使用DI容器来解决)。

问题是基类Controller类还需要一些依赖项(或参数), 例如,查看文件夹的路径。问题是 - 在何处以及如何将参数传递给基础控制器类?

$dic = new Dic();

// Register core objects: request, response, config, db, ...

class View
{
    // Getters and setters
    // Render method
}

abstract class Controller
{
    private $view;

    public function __construct()
    {
        $this->view = new View;

        // FIXME: How / from where to get view path?
        // $this->view->setPath();
    }

    public function getView()
    {
        return $this->view;
    }
}

class Foo_Controller extends Controller
{
    private $db;

    public function __construct(Db $db)
    {
        $this->db = $db;
    }

    public function barAction()
    {
        $this->getView()->some_var = 'test';
    }
}

require_once 'controllers/Foo_Controller.php';

// Creates object with dependencies which are required in __construct()
$ctrl = $dic->create('Foo_Controller');

$ctrl->barAction();

1 个答案:

答案 0 :(得分:0)

这只是一个基本的例子。为什么$ view是私有的?有充分的理由吗?

class View {
  protected $path;
  protected $data = array();

  function setPath($path = 'standard path') {
    $this->path = $path;
  }

  function __set($key, $value) {
    $this->data[$key] = $value;
  }

  function __get($key) {
    if(array_key_exists($key, $this->data)) {
      return $this->data[$key];
    }
  }
}

abstract class Controller {
    private $view;

    public function __construct($path)
    {
       $this->view = new View;

       $this->view->setPath($path);
    }

    public function getView()
    {
        return $this->view;
    }
}

class Foo_Controller extends Controller {
    private $db;


    public function __construct(Db $db, $path)
    {
        // call the parent constructor.
        parent::__construct($path);
        $this->db = $db;
    }

    public function barAction()
    {
        $this->getView()->some_var = 'test';
    }

    public function getAction() {
      return $this->getView()->some_var;
    }
}

class DB {

}

$con = new DB;
$ctrl = new Foo_Controller($con, 'main');

$ctrl->barAction();
print $ctrl->getAction();