In a traditional cakephp app development, I.e, if you are not building a pluigin and want to use a custom component in another component, the cakephp docs say you should simply register the component's name in a protected property that has an array value of the custom component's name you want to use, like so : protected $components = ['Existing'];
Lets get to an example:
// src/Controller/Component/CustomComponent.php
namespace App\Controller\Component;
use Cake\Controller\Component;
class CustomComponent extends Component
{
// The other component your component uses
protected $components = ['Existing'];
// Execute any other additional setup for your component.
public function initialize(array $config): void
{
$this->Existing->foo();
}
public function bar()
{
// ...
}
}
// src/Controller/Component/ExistingComponent.php
namespace App\Controller\Component;
use Cake\Controller\Component;
class ExistingComponent extends Component
{
public function foo()
{
// ...
}
}
How about a situation where we want to use a custom component in another component this time, in a cakephp plugin context?
Easy. We can simply do that by prefixing the plugin name before the name of the component like so: protected $components = ['PluginName.Existing'];
Lets get to an example:
// src/Controller/Component/CustomComponent.php
namespace App\Controller\Component;
use Cake\Controller\Component;
class CustomComponent extends Component
{
// The other component your component uses
protected $components = ['PluginName.Existing'];
// Execute any other additional setup for your component.
public function initialize(array $config): void
{
$this->Existing->foo();
}
public function bar()
{
// ...
}
}
// src/Controller/Component/ExistingComponent.php
namespace App\Controller\Component;
use Cake\Controller\Component;
class ExistingComponent extends Component
{
public function foo()
{
// ...
}
}
This same principle applies to helpers, behaviours, etc.
That should be all. This can be confusing sometimes especially in situations where the results you get when you google-search around these concepts often lands you on the traditional cakephp documentation.
Here is the plugin specific documentation for more info.
Also, check out a cakephp plugin for handling cloudinary media uploads I built: Cakephp-cloudinary
I'm on twitter
Top comments (0)