The Problem with MVC
The Model-View-Controller (MVC) architectural pattern is a great start to making your websites and web applications more sophisticated. However, there are limitations.
As a professional web developer that uses the CodeIgniter framework (strictly MVC), I have had extensive, first-hand experience with MVC. At first, I thought it was great. It was so intuitive and well organized. The libraries and helpers were excellent. However, as one of my sites grew and evolved into the behemoth that it is today, it became apparent that MVC was not cutting it. As the number of files being developed grew from tens to hundreds to thousands, the ability to make systematic changes became increasingly complex.
Two problems had become apparent:
- As I rolled out new applications and subsystems, it would have really helped to be able to encapsulate that functionality, both programatically and structurally.
- On several occasions I found myself wanting to call a function in one controller from another controller.
So through some research, I realized that I was not the only developer out there who found the MVC architecture limiting. In fact, there was a solution to this problem: HMVC.
Hierarchical Model-View-Controller (HMVC) Architectural Pattern
As discussed previously in my post MVC FOR PHP: WHAT IS MVC AND HOW DOES IT APPLY TO THE WEB?, the MVC architectural pattern relies on the “triad” of components depicted below:
HMVC still uses this triad, but instead of limiting the developer to this single MVC environment where all controllers are in the same
./controllers/ base path, all models are in the same
./models/ base path, and all views are in the same
./views/ base path, HMVC allows developers to designate separate “modules” to house their own models, views, and controllers directories inside their own unique paths. For example, with HMVC a developer is not limited to:
But instead, the developer now has the option to do something like this:
And so on. So the HMVC can be diagram actually consists of several MVC triads relating like so:
Benefits of HMVC
The following are the main benefits of implementing an HMVC architecture:
- Modularity: HMVC makes it easier to interchange chunks of code through encapsulation of functionality.
- Organization: HMVC allows each module to contain its own models, views, and controllers directories, keeping related files contained.
- Extensibility: By promoting modularity, HMVC allows systems to be more easily extended by simply adding or replacing modules.
- Reusability: Since modules can call each other, HMVC allows for code to be easily reused.
- MVC FOR PHP: WHAT IS MVC AND HOW DOES IT APPLY TO THE WEB?
- HMVC: an Introduction and Application
- HMVC: The layered pattern for developing strong client tiers