How to create reusable function library in CakePHP 4x?

Hi everyone.
I have several functions that are repeated in the different controllers of the application. I would like to know where I can place these functions so that I can reuse them in all the controllers of the App and also how should I call them?
Thanks in advance for the help.

Knowing where to put code can be pretty hard but let me try to help you.

CakePHP itself has 4 built-in reusable parts for each layer of the MVC

  • For reusable code in multiple controllers => components
  • For reusable code in multiple models => behaviors
  • For reusable code in multiple templates => helpers and elements

BUT these are only meant for specifically those usecases/layers, NOT sharing functionality between them or connecting them.

I would also recommend you watch my Cakefest Talk about Utility classes from 2021

In there you will see that you can create your own generic PHP classes and use them in the CakePHP framework. How you build/structure your own classes is up to you and will definitely be a long journey of learning, breaking things, fixing them and getting better :wink:

1 Like

Thanks bro.
I will investigate about that.
Your answer was very helpful.

Additional to KevivPfeifer reply you can use also the «Traits approach» according to your needs. See how core does this approach. See Cake\View\CellTrait for example.

Thks my friend for your help.