CakePHP: How to create a component

What is a component?

Component is a simple class file which contains the common code or logic. Component can be shared between our application’s controllers. CakePHP comes with some good components, so you can perform various common tasks like session handling, cookies related things, etc.

Component is a correct option when you need some things in different controllers. Using component, we can reuse the code and make our controllers clean. Apart from the in-built components of CakePHP, we can create our own component for some common functionality.

How to create a component?

Creating a component is simple. We need to create a class file in our Component directory. Create a file in app/Controller/Component directory and name it CommonComponent.php. The basic class structure of a component looks like below,

Please note that, every component class must extend the main Component class.

Let’s add one function in our component. For example, a function to generate a random password string.

Now we can add our common code in this component and use it between different controllers. We can also use other components in our components.

How to include a component in our controller?

We can include our component in controller by simply adding its name to $components array. Please note that, we only need to add class name of component – without “Component”. For example, to use our CommonComponent,

After adding this, we can use this component by using $this->Common similar to other components. If we include component in our AppController, it will be available in all other controllers, no need to include it in each controller file.

For example, to use our generatePassword function in UsersController,

 

Magic Methods

CakePHP provides some callbacks or magic methods for components. We can use these callback methods to fulfill our needs.

initialize(Controller $controller)

This method is called before the controller’s beforeFilter method.

startup(Controller $controller)

This method is called after the controller’s beforeFilter method but before the controller executes the current action handler.

beforeRender(Controller $controller)

This method is called after the controller executes the requested action’s logic, but before the controller’s renders views and layout.

shutdown(Controller $controller)

This method is called before output is sent to the browser.

beforeRedirect(Controller $controller, $url, $status=null, $exit=true)

This method is called when the controller’s redirect method is called but before any further action. You can reset the redirect url or disable the redirection from here.

You may also like...