Search code examples
cakephpcakephp-2.0cakephp-modelprivate-methods

Should controllers avoid private functions at CakePHP?


I was wondering if controllers at CakePHP should not contain any private function which is not accessible by URL.

Sometimes some functions such as add or delete can be so large that I prefer to divide them. Should I put that functions inside the model instead of making then private on the Controller?

Thanks.


Solution

  • Yeah it's probably for the best if you keep your methods in the Model. Like you yourself have mentioned in the comment, "keep models fat and controllers thin". The controller is just a medium which is supposed to interact between model and view.

    The problem comes when you have to deal with changes in datasources, tables. If your controllers are fat, you would have used the fields everywhere, and now you will be left with cleaning the whole setup in places where it wasn't supposed to be.

    The added benefit of methods in models is that you can call it from other models and reuse the code. For example:

    class User extends AppModel {
    
         public function getAllActiveUsers() {
             // return active users
         }
    
    } 
    

    The above method can be accessed by every other methods in both model and controller, which is related to the User.

    If you need such functions elsewhere and if you don't have them defined in the User model, you will either end up redirecting it to the controller or writing the whole logic all over again.

    The redirecting thing isn't that bad but consider what happens if you have rewritten the logic elsewhere, and then your implementation of ActiveUsers changes. You will end up having to correct things everywhere.

    However, there are a few things that have to be done in controller. For example, if I have to calculate the distance between the user's geolocation and all the matching restaurants for a nearby distance, I should do this in the controller. But it is in the best interest that the controller is left thin, and components exist for this purpose. You can create your custom components for complex and lengthy logic.