Search code examples
phpcakephpcakephp-model

CakePHP: where to put shared model logic?


I'm working on a legacy CakePHP project (CakePHP 1.3) and I'm having a hard time figuring out where to put shared model logic. I come from a Laravel background and would normally make a service class or Laravel facade and use it where needed, but that doesn't seem to be the Cake way of doing things. (Maybe I'm wrong about this??)

The project uses a hash to generate unique database keys. The hash function itself is in /vendors. There are several helper functions used to generate the hash, decode the hash etc. and these are currently repeated in several different models. Ideally, I would like to extract these functions to a single class and call them statically from the models that need them: Hash::make($params), Hash::decode($hash) etc. How could I set this up in a CakePHP application?


Solution

  • CakePHP 1.3 is very old. So you're basically dealing with a version of the framework that is not even using namespaces. However, this doesn't prevent you from using them. Also it's no longer officially supported.

    If you call it model or service, I don't think it matters much as long as you do proper separation of concerns which is what you seem to care about - which is good.

    Just create whatever classes you need to abstract your logic in the model folder. In your special case I think a behavior would work as well instead of implementing a ton of static methods which leads to tight coupling. Create a HashBehavior to get re-useable code on your table objects. Actually I dislike Laravel for all it's statics (Yea, I know about the facades but still...). Sounds like you inherited some piece of not so well written code, good luck with your refactoring!