What is the best practice location for common functions?

I’m converting our web app, written in old, traditional PHP5-style coding, into modern PHP8 using Cake. I have this one file called utils.php which is a collection of functions used repeatedly throughout the app. In the old code, I would simply ‘require’ it and use the functions.

What is the proper way to do this in CakePHP/ORM/OOP? Do I just make a simple utility class where every method is static and call from anywhere? If so, where do I locate that class file? It’s not really a plugin, nor a component (or is it?). I figured it needs to be located in some path that will auto-load it.

if you want to autoload it via classes it needs to be inside the src folder since the App namespace is mapped to that folder (see your composer.json)

you can of course just use the oldstyle functions as well. All you’d have to do is put that file inside your config folder and require it inside the bootstrap.php and thats it.

It of course may be a good idea to refactor some methods into cakephp specific parts like you said but only under certain conditions:

  • Controller Components were initially meant to ONLY contain logic which is shared across controllers but with the introduction of the Dependency Injection Container in CakePHP 4.2 they pretty much have lost their value.
  • Behaviors are shared logic between your table classes inside your model
  • View Helpers and Elements are ways to get a bit more structure into your template

Everything else (and as said above what was previously Controller Components) should nowadays just be implemented as a service class. See https://www.youtube.com/watch?v=z3E_UdH1XeE on how Composer Autoloading works and how you can basically put your files anywhere you like inside the src directory.

Service class and utility class are basically just the same. Just a generic PHP class which contains the logic you want to have

Also see my latest workshop on how to use the Dependency Injection Container with testing: