【发布时间】:2012-03-08 14:49:45
【问题描述】:
我有一个抽象的基础控制器类,所有的动作控制器都派生自它。
构造时的基本 Controller 类初始化 View 对象。这个 View 对象被所有的动作控制器使用。每个动作控制器都有不同的依赖关系(这通过使用 DI 容器来解决)。
问题是Controller基类还需要一些依赖(或参数), 例如,查看文件夹的路径。问题是 - 在哪里以及如何将参数传递给基本 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();
【问题讨论】:
-
私人 $view;为什么 $view 是私有的?你什么时候知道要加载哪个视图路径?在动作控制器内部?那么这很容易做到。
标签: php dependency-injection base-class