Reference another component from within a component in CakePHP 4
Referencing components in CakePHP 4 from within another component
This example shows you how to reference another component from within a separate component in CakePHP 4. For example, you can call functions in Component A from Component B.
First, load your component in your CakePHP app.
One method to do this is to add the following to your initialize function in AppController.php:
/src/Controller/AppController.php
public function initialize(): void { parent::initialize(); .... $this->loadComponent("componentA"); ...
Next, reference the loaded componentAComponent (/src/Controller/Component/componentAComponent.php) from within componentBComponent (/src/Controller/Component/componentBComponent.php)
First, In componentBComponent.php, load componentA in your Constructor or initialize function, by adding the following:
function __construct() { ... $this->componentA = new componentA(); ... }
Now, you can use componentA within your componentBComponent.php, like follows:
function myFunction() { ... $someValue = $this->componentA->getSomeValue(); ... }