Defining your own components in cakePhp

1 Jan

Although cake is shipped with some standard components like Email, security, sessions and authentication etc, however it is like piece of cake to define your own components in cakePhp

If certain code is used again and again in your application, it is better to define your own component and put that code in it. The code written in component can be reused wherever you want in your application.

In your “/app/controllers/components/” directory create a file say math.php and put the following code in it.

<?

class MathComponent extends Object

{

function sum($x,$y){

return $x+$y;

}

}

the code above is very simple to understand. To define a component you will need to extend it form Object class. And then define your own function.

Later in your controller, you can call this method as

<?php

class IndexController extends AppController

{

$components = array('Math');

function index()

{

$x = 5;

$y = 5 ;

$sum = $this->Math->sum($x,$y);

}

}

in the first line $component = array(‘Math’); we tell the controller that we will use Math component in our action. And then in line $sum = $this->Math->sum($x,$y), we call the method we have already defined in our component.

If you want to access specific component within another, you can write

<?php

class MyComponent extends Object

{

var $components = array('Math');

function doStuff()

{

$result = $this->Math->sum(5,5);

}

}

If you want to access specific model in your component, simply write

$user = ClassRegistry::init('User');

here ‘User’ is the name of the model we want to use in our component and then

$totalUsers = $user->find('count');

2 Responses to “Defining your own components in cakePhp”

  1. Asim Zeeshan February 26, 2009 at 2:48 pm #

    Thanks for sharing this article

  2. manu tyagi June 13, 2009 at 5:23 am #

    simply awesome

Leave a comment