Suppose in our application we need to perform a mathematical operation in many different parts, then we could create our own component to use in many different controllers.
1. First create a file named MathComponent.php in app/Controller/Component/MathComponent.php. The structure of this file is like:
App::uses('Component', 'Controller');
class MathComponent extends Component {
public function doComplexOperation($amount1, $amount2) {
return $amount1 + $amount2;
}
}
In the above code doComplexOperation() function having two arguments $amount1 and $amount2 will return addition of two numbers , passed as a arguments.
2. Now include your component in your controller. You can declare a set of parameters that will be passed on to the Component’s constructor.
public $components = array(
'Math' => array(
'precision' => 2,
'randomGenerator' => 'srand'
),
'Session', 'Auth'
);
In this code above, we can use MathComponent in the application’s controllers by placing the component’s name (without the “Component” part) in the controller’s $components array.
0 Comment(s)