【发布时间】:2011-07-21 05:11:57
【问题描述】:
我有一些我想在 CakePHP 任务中使用的组件代码,但我不确定我是否以正确的方式引导控制器。
作为一个简化版本,我有两个组件在通过扩展的 AppController 访问时运行良好。一个组件包含另一个组件,因为它调用另一个组件。
第一个组件:
class BigBrotherComponent extends Object {
var $Controller = null;
var $components = array('Sibling');
function startup(&$controller) {
$this->Controller =& $controller;
}
function doThis() {
$this->Controller->loadModel('SampleModel');
$this->Sibling->doThat();
}
}
第二个组件:
class SiblingComponent extends Object {
var $Controller = null;
function startup(&$controller) {
$this->Controller =& $controller;
}
function doThat() {
/* Doing stuff */
}
}
为了让我从命令行进行操作,我定义了一个 Shell 和一个 Task。这是任务,虽然我不确定我做对了。
App::import('Core', 'Controller');
App::import('Component', 'Session');
App::import('Component', 'BigBrother');
class BigBrotherTask extends Shell {
var $Controller;
var $BigBrother;
function initialize() {
$this->Controller =& new Controller();
// add session to controller, because some components access $this->Controller->Session->setFlash();
$this->Controller->Session =& new SessionComponent();
$this->Controller->Session->startup($this->Controller);
// Initialise the component
$this->WordToText =& new WordToTextComponent();
$this->WordToText->startup($this->Controller);
}
function doThat() {
$this->BigBrother->doThat();
}
}
当 BigBrother 组件不包含任何它自己的组件或引用 BigBrother 组件中的 Controller 之外的任何其他组件时,这种类型的任务很有效。如您所见,我不得不为 Session 组件做一些小事。
有没有更好的方法来初始化和使用任务中的组件,可以正确初始化组件和子组件?
【问题讨论】:
标签: cakephp cakephp-1.3