Friday 6 July 2012

Create CakePHP Component

When we require any code for many controllers or different parts of application we can create component in CakePHP Framework. Suppose we need a complex mathematics calculation in every controller or different parts of application we create a math component to share in different controllers. Let we create a Sum component to return sum of two numbers, we can create this component in the path /app/controllers/components/math.php with below code:
class SumComponent extends Object {
function sumTwoNums($amount1, $amount2) {
return $amount1 + $amount2;
}
}
?>

Above Sum component is extending Object class not Component, because if we extend Component which can create infinite redirect issues when component is combined with another Components.
Include Component in Controller where we need it.
var $components = array('Sum');
Calling Component functions inside Controller by below code:
$this->Sum->sumTwoNums(4,8);

No comments:

Post a Comment