Components in CakePHP4: Creating a Component and Using Components in Controllers

Components in CakePHP4 - Creating a Component and Usage in Controllers

Components are re-usable bits of code you can call anywhere throughout your application. Components can be essentially used in place of a controller (e.g. when you need a calculation), and within controllers (e.g. when you need that calculation in many places). 

For example, you might want to return a certain calculation in several areas within your app.  Components let you put that calculation in one place, and call it from many controllers in your application.

In this example, we create a simple component to return unique id, for use in any of our CakePHP4 controllers.

Step 1: Create Your Component: Create the file \src\Controller\Component\getUniqueIdComponent.php in your CakePHP4 app, and paste the following code into the file:

<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Controller\ComponentRegistry;

class getUniqueIdComponent extends Component {

    public function createUniqueId() {
        return uniqid();
    }

}

 

Step 2: Load the component in your src\Controller\AppController.php (or other initialize() function within another controller) to make it available:

public function initialize(): void {
     ...

    $this->loadComponent("getUniqueId"); // Load GetUniqueIdComponent

    ...

 

Step 3: Use your new getUniqueIdComponent in a controller by calling the createUniqueId() method in that class from /src/Controller/Component/getUniqueIdComponent.php:

Below is an example of usage in any method within your CakePHP 4 controller(s), since it's been loaded in your AppController.php above..

public function index() {
    debug($this->getUniqueId->createUniqueId());exit;
    ​...

 

Share this Post