如果要在元件中存取控制器的實例(instance),需要實作元件的initialize()或startup()方法。這兩個特殊的方法接收一個到控制器的引用作為第一個參數並且被自動呼叫。 initialize()方法在控制器的beforeFilter()方法執行前被自動調用,startup()方法在beforeFilter方法執行後自動呼叫。如果因為某些原因你不想startup()方法在控制器執行構築操作的時候被調用,那麼可以設定類別成員變數$disableStartup為true。
如果你想在控制器的beforeFilter()之前乾點什麼的話,initialize()方法是最合適的選擇。
class CheckComponent extends Object {
class CheckComponent extends Object {
//在Controller::beforeFilter()之前被呼叫
function initialize(&$controller) {
// saving the controller reference for later this- & $controller;
}
//在Controller::beforeFilter()之後被呼叫
function startup(&$controller) {
}
function redirectSomewhere($value) {
// 使用的方法
// this->controller->redirect($value);
}
}
?>
// 其他需要使用的元件
var $components = array('Session', 'Math'); function doStuffs { $ >Math->doComplexOperation(1, 2);$this->Session->write('stuff', $result);
}
}
?>
}
?>
}
?>
// 其他需要使用的組件
var $components = array('Session', 'Math');
function doStuff() {
$res );
$this->Session->write('stuff', $result);
}
}
?>
在組件中使用或存取模型(model)很推薦這並不是很推薦;不過這並不是很推薦種可能性也不是沒有,在這種情況下,你需要手動的生成模型的實例來使用。以下是一個例子:
class MathComponent extends Object {
function doComplexOperation($amount1, $amount2) {
return $amount1 + $amount2; }
, $amount1 + $amount2;
}
🜎, 8%🜎, $userInstance = ClassRegistry::init('User');
$totalUsers = $userInstance->find('count');
return ($amount1 + $amount2) / $totalUsers;
}
}
?>
class MathComponent extends Object {
this section. Please help out and translate this.. More information about translations
Sometimes one of your components may need to use another.
You can include other components in your
You can include other components in your component the exumsecludes.
class CustomComponent extends Object { var $name = "Custom"; // the name of your componentvar $components = array( "Existing" ); itialize (&$controller) {
$this->Existing->foo();}
function bar() {
class CustomComponent extends Object {
var $name = "Custom"; // the name of your component
var $components = array.com
function initialize(& $controller) {$this->Existing->foo();}function bar() {// ...}? class ExistingComponent extends Object {
var $name = "Existing"; function initialize(&$controller) {$->Parento> ) ) {
// .. . }
}
?>
class ExistingComponent extends Object {
var $name );
$this->Parent-> bar();
}