MVC Best Practices – Private Non-Action Functions in Controller

code-qualitymvcPHP

Sometimes action functions in the controller class can become huge and nasty, with many-many lines of code to simply control the flow of data from the Model to the View. At some point these huge functions completely lose track of the basic principles of good code, i.e. only doing one thing, being small, readable and manageable etc.

Would it be considered good practice to break these huge action functions into smaller private functions in the controller class or should the need of such optimization mean we should rather add them in the model?

I would vote for having the smaller functions as private in the controller so that they are relative to the action, but I have heard arguments that the controller should preferably be simple while the model can get huge and clumpy; and was just wondering which one would be the most preferred method.

Best Answer

Might not be the best analogy but, think about the controller the same way as you would think about a spider's web. Its sole job is to catch flies (requests) for the spider (underlying layers) to digest. The web can catch and hold smaller or larger flies (models). A spider's web role is not to digest the prey, although it can be used in this purpose. The thinner and cleaner the web, the easier for the spider to make a living.

You could apply somewhat the same logic to your MVC application. The huge and nasty functions you describe are most likely behavior of the model and they should belong in the model (note that the model is not only the object that's being displayed in the view). If the behavior of the model changes it's the model that should be changed and not the controller that handles it.

Also, keeping them as private methods in the controller would only clutter it and make it hard to maintain. It also makes way for a bad habit, since other people that are involved in development would be tempted to do the same, since they've seen it done before in the project.