MVC Class Access Within Components
To get access to the controller instance from within your newly created component, you’ll need to implement the startup() method. This special method takes a reference to the controller as its first parameter, and is automatically called after the controller’s beforeFilter() method. If for some reason you do not want the startup() method called when the controller is setting things up, set the class variable $disableStartup to true.
If you want to insert some logic before a controller’s beforeFilter() has been called, use the initialize() method of the component.
<?php
class MathComponent extends Object {
//called before Controller:beforeFilter()
function initialize() {
}
//called after Controller::beforeFilter()
function startup(&$controller) {
}
function doComplexOperation($amount1, $amount2) {
return $amount1 + $amount2;
}
}
?> <?phpclass MathComponent extends Object {//called before Controller:beforeFilter()function initialize() {}//called after Controller::beforeFilter()function startup(&$controller) {}function doComplexOperation($amount1, $amount2) {return $amount1 + $amount2;}}?>
You might also want to utilize other components inside a custom component. To do so, just create a $components class variable (just like you would in a controller) as an array that holds the names of components you wish to utilize.
To access/use a model in a component is not generally recommended; however if weighing the possibilities this is what you want to do you'll need to instanciate your model class and use it manually. Here's an example:
<?php
class MathComponent extends Object {
//called before Controller:beforeFilter()
function initialize() {
}
//called after Controller::beforeFilter()
function startup(&$controller) {
// Saving a reference to the controller on the component instance
$this->controller =& $controller;
}
function doComplexOperation($amount1, $amount2) {
return $amount1 + $amount2;
}
function doUberComplexOperation ($amount1, $amount2) {
$userInstance = ClassRegistry::init('User');
$totalUsers = $userInstance->find('count');
return ($amount1 + $amount2) / $totalUsers;
}
}
?> <?phpclass MathComponent extends Object {//called before Controller:beforeFilter()function initialize() {}//called after Controller::beforeFilter()function startup(&$controller) {// Saving a reference to the controller on the component instance$this->controller =& $controller;}function doComplexOperation($amount1, $amount2) {return $amount1 + $amount2;}function doUberComplexOperation ($amount1, $amount2) {$userInstance = ClassRegistry::init('User');$totalUsers = $userInstance->find('count');return ($amount1 + $amount2) / $totalUsers;}}?>

login to add a comment