CakePHP includes some components which you can use to do specific tasks within your controllers but it may not be sufficient and you may want to create your own component.
Creating your own CakePHP component is quick and easy. I’ll use a currency conversion component here as an example.
1. Create CakePHP Component
First, the name of the component will be
CurrencyConvert so as a result, the filename will be
currency_convert.php and the class name will be
CurrencyConvertComponent and extends to
Object. This is standard with CakePHP, always follow this convention.
So create a PHP file named currency_convert.php and place it inside
app/controllers/components/ in your CakePHP installation. Here is what the
currency_convert.php file will look like:
2. Load CakePHP Component
Now that you have your custom CakePHP component ready, you can load it in your controllers.
First, you need to load it in a controller or even globally in all controllers. To load it in a single controller, you’ll add the code below as a class property to the specific controller(s). To load it globally for all controllers, open
app/app_controller.php file and put the code as a class property on the
Please note that if the
$components class property already exist, you can just add it to the
Array. You don’t want to specify the property again, else the latter will overwrite the first one.
3. Using CakePHP Controller
Now you can use the CakePHP component in your controller(s). In any controller function/method, you’ll use it like this:
The above is just an example as if our controller were named
ModelController and the function/method was index. You can use it this way in any of your own controllers as needed.