Programming Tips for using a Model-View-Controller (MVC)
Using a Model-View-Controller (MVC) approach is often a smart way of programming. Your code is separated into modules and classes, making it easier to divide and conquer your way through a project. Any bugs in one module shouldn’t affect the code in another module. Furthermore, the template is separated from the code, so its easier to make changes in this way too.
Now there are good ways to use an MVC, and really awful ways of doing it. Here are some tips:
- Do all your database work in the controller before sending it to the template. The template shouldn’t be doing any database work or calls at all. It should merely be concerned with formatting and display.
- Use a switch method in your dispatch that calls a function. Its awful to see the amount of work that gets called in dispatch methods. You end up running all over the place trying to trace multiple functions. Rather let each event call its own function, and all actions for the event performed in this function.
- Avoid over-complicating a function. As a rule, if I see a function as over-complicated, it is a sign to me that the function needs to be broken up into further sub functions.
- The last one is a bit tricky. The controller’s functions should only be with ‘controlling’ the module. Often I notice that some of the functions or sub functions would be useful to others as well. If you pick up this trend in your controller, then that function needs to be moved to a separate class. Functions in a controller are only available to that controller. Functions in a class are available to all controllers and modules.
MVCs are great but their are ways to experience the maximum benefit in the power of MVC programming. Otherwise, you just end up complicating things for yourself.
