Cakephp plugin Development: using custom component in another component.
Chidiebere Chukwudi

Chidiebere Chukwudi @jovialcore

About: Software Developer. php| laravel | cakephp | vuejs/Nuxt | wordpress | Bootstrap | Tailwind

Location:
Nigeria
Joined:
Jan 10, 2018

Cakephp plugin Development: using custom component in another component.

Publish Date: Apr 20 '23
0 0

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()
    {
        // ...
    }
}
Enter fullscreen mode Exit fullscreen mode

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()
    {
        // ...
    }
}
Enter fullscreen mode Exit fullscreen mode

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

Comments 0 total

    Add comment