9.2. Creating your own

To create a component, add a file in app/controllers/components/ directory.

Let us assume you created foo.php. Inside of the file you need to define a class that corresponds to the file name (appending the word 'Component' to the file name). So in our case you would create the following contents:

Example 9.1. A simple component

class FooComponent extends Object
{
    var $someVar = null;
    var $controller = true;
 
    function startup(&$controller)
    {
        // This method takes a reference to the controller which is loading it.
        // Perform controller initialization here.
    }
 
    function doFoo()
    {
        $this->someVar = 'foo';
    }
}
	


Now, to use your component, you need to add the following code in your controller's definition:

	var $components = array('Foo');
	

Inside of that controller you could now use:

	$this->Foo->doFoo();
	

A component gets access to the controller that loaded it through the startup() method shown above. This method is called immediately after Controller::beforeFilter(). This allows you to set component properties in the beforeFilter method, which the component can act on in it’s startup() method.

To use your models inside of your components, you can create a new instance like this:

	$foo =& new Foo();
	

You can also use other components inside your component. You simply have to declare in your component which components you want to use. In the example below it is the session component.

	var $components = array('Session');