MVC – a Problem or a Solution?

Tweet

Repositories, Adapters, MVC with all it cousins, SOLID, RTFM… As a (PHP) developer, those words are thrown at you from every corner of the web. And I hate it, I’ve had enough. Stop telling me what to do and show me those kittens instead.

Software solves problems

We don’t just write software. Code doesn’t fall out of the sky into our files. We analyze the requirements, split them into small problems we know how to solve, and then we solve those small problems. Every line of code you write, have written and will ever write solves a certain problem. Be it to save the world, show kittens on a screen or make it look good in IE8. It’s there for a reason, don’t you touch it!

Problems are solvable and the solutions for these problems become part of something bigger. A black box that satisfies all initial requirements. But how do we solve these problems? Is my solution the best solution? Will other developers (or me in 2 months) understand what I did here?

One solution fits all

When solving the web-application problem, we are forced to use MVC. The dev community often frowns upon those who don’t use it, but seldom lets those they’re frowning upon ask why.

So why is MVC the best? Commonly regurgitated reasons are:

  • Reduced Code complexity
  • Code reuse
  • Increased flexibility
  • Decoupled code

Cool, sounds nice, but…

  • Is it true?
  • Do all other patterns lack these cool things?

The answer is no.

MVC doesn’t solve the Code complexity problem. It doesn’t solve the code reuse or no-flexibility problem either. And it doesn’t guarantee decoupled code.

Developers guarantee reduced code complexity. It’s us coders, programmers, developers and artists that write flexible, decoupled and reusable code. We need MVC as much as we need jQuery for document.getElementById(). We’ve been building great software before anyone had heard of MVC and we will continue building great stuff without MVC.

Don’t forget that MVC is a pattern, not a solution. It stands in line with all the others. Adapters, Factories, Singletons, Modules, Interpreters, Observers…

Patterns don’t solve problems, they help us

Patterns help us write flexible, decoupled and easy to use code. A pattern is a best practice that a developer can use to solve problems. Those best practices vary depending on the type of problem you are solving, there is no top 5. A boat might be really good at crossing water, but it can’t plough a field.

Each pattern has its strength and weaknesses and is tailored to tackle a certain situation. The Factory pattern for instance is really good at creating Objects. The Module pattern helps us write software modules in a language that doesn’t (or only partially) support modules (e.g. JavaScript). The Observer pattern’s strength is event handling and MVC helps us in decoupling layout, data manipulation and controllers.

But MVC is heavily abused, and here is why:

Somewhere down the road, someone decided that this was the best approach for everything written in PHP and accessible with a browser. Then came along the rule that a Model should have a 1-on-1 relation to a row in a database, Controllers should be thin and views have to be written in a templating language that compiles to PHP.

Then, someone noted that ‘thin controller’ is not always the best approach. They thus created the rule of fat controller, thin model.

Several iterations later, we made poor MVC give birth to HMVC, MVA, MVP, MVVM, PAC…

MVC is the new Singleton (or IE8)

Sadly enough, MVC isn’t the only abused pattern. As Keith nicely points out:

We needed something that looked like a global and acted like a global but wasn’t really a global.

Suddenly the Singleton pattern was showing up everywhere in our code. You could write crappy code without people complaining about the use of global $var. Instead we used the Singleton pattern, Global::getInstance()->var and called it OO.

Patterns are cool, developers aren’t

Don’t get me wrong, patterns are there to be used. But use them wisely. Use them together. There is nothing worse then a developer using the wrong pattern for the wrong reason with the wrong intentions.

So please, I beg you. Don’t abuse patterns.

Don’t reinvent the wheel. You are not the first developer trying to create modules in JavaScript, neither are you the first one developing event handling software. A lot of smarter, more trained professionals have done the exact same thing before you.

Having trouble separating your MySQL from your PHP? Are you writing SELECT * FROM in your HTML? MVC will probably help you, or maybe Multitier architecture is a better fit for you.

Having troubles with lazy loading/reading config data? Singleton could help here.

Is creating an object of a certain class a pain in the ass? The factory pattern can really help you stay DRY.

Having troubles getting 2 services to communicate with each other? Adapters can help.

Conclusion

Depending on the situation, and the problem at hand, different patterns can help you write robust, secure and understandable code. Just be careful using them – if you catch yourself using the MVC pattern for a 1-pager, ctrl+a del.

May the patterns be with you!

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://thecodingbox.me/ Harpreet Bhatia

    hehe nice. I’m php developer and like 4 years ago, suddenly there were queries. “can you develop in CI, or any other MVC”
    The problem starts when new developers try to imitate celebrity developers. Then its like a trail.
    First Codeigniter, Kahona(or whatever its called), and now Laravel.
    I am not blaming. I have been using codeigniter since. Got better projects and stuff. sometimes they save time sometimes the don’t.

    Nothing is simple, code is always complex as it gets bigger.

    • JY

      simple solutions do exist. work smarter not harder.

  • http://wojciechfornal.com Wojciech Fornal

    I don’t see anything wrong in using MVC for a 1-pager. It is still better than mentioned SQL inside HTML (I shouldn’t say that in public but I was once asked to maintain online e-commerce with “solutions” like that). MVC doesn’t mean that you have to incorporate sth of the scale of Symfony 2. You can always craft small MVC-like something on your own for your 1-pager :)

    • http://moelleken.org/ Lars Moelleken

      SQL inside HTML? WTF? I think we are in the good position today to choose some components via “composer” to create a small / secure code-base for our PHP-Projects and if you create a simple 1-pages, maybe you can choose e.g. “slim”, “twig”, “swiftmailer”, “htmlpurifier” and “php-activerecord” … if you will, you can also add a small “MVC”-library e.g. “slim-mvc” (or create your own and push it to github) :)

      Happy coding @ all!

      • http://wojciechfornal.com Wojciech Fornal

        Yeah, some people mix PHP snippets inside HTML not only for templating purpose :)

        • rubyotero

          when in starting in php… im guilty on this

  • Jiri Fornous

    Mvc is more paradigm than pattern and is almost impossible to avoid. In general form it only describes separation of user interaction with your app into tiers. In PHP world many programmers came in last couple years had taken Martin Fowler’s book of design pattern and started to claim this is Mvc. Mvc can be found everywhere – be it component based framework like Yii, Symphony’s “mvc” or hand made application framework. Mvc can be seen even within RPC APIs etc.

  • Stefan Priebsch

    Interesting article. I wish you had elaborated a bit more on MVC as a pattern itself. The problem MVC originally was set to solve is to synchronize multiple views on the same data (a.k.a model). To achieve this, two subject-observer relationships (controller observes view, view observes model) are used.

    Now here comes the fun: not only does this problem not exist for PHP applications (it may exist in the frontend, but not on the server side), but also there is a system boundary between the view (which is displayed in the browser) and the server, making both subject-observer relationships technically impossible to implement.

    What people call MVC on the web is very, very different from the original MVC pattern. And personally, I am not convinced server-side MVC makes any sense.

    • Joeri Sebrechts

      PHP’s MVC frameworks are heavily inspired by the Java world, whose patterns largely derive from desktop app development, where they made a lot of sense, and were then adapted into web development. Ofcourse, in Java web dev MVC still kind of makes sense, because model objects are long-lived across requests, so you can render multiple views from the same model.

      In PHP I would agree the pattern makes not that much sense. There is some benefit to be had by separating data logic from business logic from response generation. However, you can’t escape the fact that handling a request in PHP is inherently procedural. It’s a step-by-step filtering and adapting of input to output, with some side-effects along the way. I find that the MVC layers obfuscate the process, instead of illuminating it.

  • Taylor Ren

    Well, first of all, I have to agree with +Jiri Fornous, I won’t call MVC a pattern.

    There are deeply rooted synergies between MVC and a typical web app components.

    Model MySQL server (Data)
    Controller PHP (Code)
    View HTML (Presentation)

    Using MVC does not rule out the usage of any other patterns/technologies. For example, a user login action can retrieve data from Model, and the Controller can rely on other multi-tier authentication tool chains.

    The author is absolutely right when saying Nothing fits all and “It depends” — reminds me the famous scripts from “The Grand Budapest Hotel”. But I want to say, before a new structure comes in and it has been proved by majority that it excels MVC, I will use MVC, none the less.

    Even for a one-pager app, it helps and there are plenty of lighter MVC complied frameworks to choose.

    • abcham

      I agree, I don’t see MVC as a Pattern, more like a presentation layer, as you mention, your controller/model can delegate the solution of the problem at hand to other libraries that might follow other design patterns.

  • Vladimir Kovacevic

    I found it very difficult to use MVC in ever changing app model.

    • Tony Marston

      Why? In my implementation of MVC each Model class represents a single database table, and I generate each Model class from my Data Dictionary which imports its data directly from the database schema. I can create new tables at will, and I can modify existing tables with extreme ease – simply import into my Data Dictionary then export the revised table structure files.
      If you are having difficulties with your implementation I would suggest that your implementation is not as good as it could be.

      • Vladimir Kovacevic

        My controller usually looks like:
        $view->data = $db->fetchAll(“SELECT * FROM bunch_of_tables WHERE some_complex_query”);

        When I add/change some rows in table, I only have to change view.

        View is cached so there is no impact in performance.

        • Tony Marston

          You have a Controller which accesses the database directly without going through the Model? That is so wrong in my book. My version of MVC started off as the 3-Tier Architecture with its separate Presentation, Business and Data Access layers. The View and Controller are in the Presentation layer, and the Model is split into two so that all validation and business rules are performed in the Business layer while all database access is performed in a separate Data Access layer. This allows me to switch from one DBMS to another without having to change anything in the Business layer. My controller looks like this:
          $result = $model->getData($where);
          $view->buildHTML($model);
          This allows the Model to do much more than issue the SQL query as it may need to massage the data before it is output.
          The Controller should *NEVER* access the database directly – it should *ALWAYS* go through the Model.

  • http://www.abdmaster.com/ Ahmedul Haque Abid

    So…. are there any other patterns beside MVC that is used commonly in web apps??

    • Jeroen Meeus

      Yes. The Facade pattern for instance. Or Observer pattern (javascript event binding). Or Singleton pattern. Factory pattern (everyti you use Model::get($id) ), Strategy pattern, …

      • Tony Marston

        Why would you use the factory pattern between the Controller and the Model? Why can’t the Controller instantiate the Model directly? This seems like an unnecessary complication to me. If I can achieve something with less code then I will use less code. It is more efficient that way.

        • Jeroen Meeus

          Your controller shouldn’t need to know how to create a model. It also makes testing a lot easier. Simply have the factory create a mockobject and it will be used in your entire application wihtout having to touch anything (except the factory). If it looks like a complication to write Factory::get($id) (or $this->factory->get($id) ) instead of new Model($id); you probably have bigger problems.

          • Tony Marston

            > Your controller shouldn’t need to know how to create a model.
            Who says? That artificial rule does not exist in my universe, so I do not follow it. My Controller is passed the name of a class, it loads the class file and instantiates an object in two lines of code. What could be simpler?

            > It also makes testing a lot easier.

            I disagree. The simplest technique is always the easiest to read, execute, enhance and debug, and using a factory to create an instance is definitely not the simplest method.

            > Simply have the factory create a mockobject

            I don’t use mock objects as they achieve nothing useful.

  • http://yapf.blogspot.nl/ vinny42

    I love it when people start to argue over what MVC really is. :-)

    “if you catch yourself using the MVC pattern for a 1-pager,”

    … then that’s just fine. Really. MVC is a pattern, not a framework. If you want to separate the HTML generation from the behaviour and the datastore in an 1-pager, that’s perfectly ok.

    For that matter, using a whole framework would be ok too. It’s a human thing to equate “the final website is simple” to “the code for a simple website must be small and simple and not use anything that is generally associated with larger websites”.

    But I agree with the gist of the article: Patterns are optional solutions to common problems. If you don’t have the problem, then you may not want to use the solution.

  • Tony Marston

    The only problem with the MVC design pattern is that many developers have wildly different interpretations of what it means, and wildly different interpretations of how it should actually be implemented. The idea that you should also use other patterns such as Observer and Factory in order to “properly” implement MVC is utter nonsense.
    My own implementation of MVC comes closer to meeting the objectives of more reusable code, more flexibility and loose coupling. Note that I said “loose” coupling as code which is completely decoupled just won’t work. Tight coupling is bad whereas loose coupling is good.
    I have achieved more reusability as I have a fixed set of reusable Controllers and a single reusable View which constructs all HTML output by using XML and XSL transformations. I have an alternative View component which produces PDF output.
    All my Models are generated from my Data Dictionary, one per database table. Adding new tables, or changing the structure of existing tables, can be handled with the minimum of effort.
    This arrangement is definitely loosely coupled as any Controller can be used with any Model, and any Model can be used with either the HTML View or the PDF View.
    Some developers have artificial rules when it comes to MVC:
    – a Model can only work with a single database row.
    – a Controller can only communicate with a single Model.
    These rules do not exist in my universe, so I ignore them, and my software is all the better for it.

    • Chris Emerson

      There are no ‘rules’, just best practices. Some people do things that make no sense, but there is a lot of sense in some things that people do. Both the rules you mentioned sound like rubbish to me (I certainly don’t follow that), but there are plenty of rules that work well to create a maintainable, testable (note I mean automated testing, not manual testing) and flexible framework.

  • eglizzy

    The goal shouldn’t be MVC. The goal should be Separation of Concerns (SoC).

    • Jeroen Meeus

      My goal is cash. But I see your point

      • Bob

        I love it!

  • Marcelo Pereira

    MVC is separation of concerns in real world.

    We developers want a Code that handles database interactions separately from other layers like presentation. Then, we call it model. If we split the model for each table or persistence object, it’s even better. Models.

    We want a Code block that handles the presentation layer isolatedly. So we call it View. But some call it templates or anything else you want. The idea is to have a separated place to put your files that shows data on the screen. Be it on a browser or on a window.

    We also want a code to make some minor validations and to glue together presentation and persistence, so we call them controllers. That is just an development approach to me. If you are separating your application in layers like that, so you are doing MVC. You don’t need a framework, you don’t need the naming convention. You just need to want a layered application.

    And when a problem occurs you know exactly where to find the issue.

  • Alex

    “if you catch yourself using the MVC pattern for a 1-pager,ctrl+a del.” What about the open-closed principle? MVC gives structure, even one-pagers should be extendable. Sure, there are one-pagers which may prove never to need extending, however the quote above “provides” a much too general rule. I highly disagree!

  • http://www.spraci.com michaelmd

    the problem is frameworks insisting on keeping a user waiting for the whole page to be built before they see anything!
    and so often they use “MVC” as an excuse for doing that.
    that’s abuse of the pattern.

    it might take a few more seconds to get all the data for the page
    , but if there is already something for the user to read, why not render it and send it to them? …Modern browsers are pretty good at handling partially loaded content, so why keep those users waiting?

    • Chris Emerson

      What has that got to do with MVC? MVC doesn’t say anything about having to build the whole page before displaying it.

  • CTN

    “seperating”

    It’s “sepArating”!!!!!

    I can’t be bothered to read anything more that you write. You could not have offended me more if you had written “looser” to mean “loser”.

    absolutely grates on my nerves.

  • Chris Emerson

    MVC is not a ‘design pattern’ as is being said so much here. It has nothing much to do with Observer, Factory, Adapter etc that are commonly referred to as design patterns. MVC is more of an architecture pattern, and design patterns may or may not (probably do) exist within that architecture as and when they are required. It’s pretty confusing to claim MVC is the same type of thing as these design patterns.

  • Maykonn Welington Candido

    MVC is an architectural pattern, not a design pattern. Makes sense to compare it to Factory or Singleton? The problem is that people understand MVC as a design pattern and MVC is related to the structural side of the software architecture and also find a solution and take as a rule.

    Be skeptical! There is no silver bullet!

  • PocketHoosier

    MV* has proliferated web development for one reason: management thinks it drives down the cost of building and maintaining software. It is the “One Pattern to Rule Them All” so that us overpaid typists can be replaced by lower priced labor.

    Raise your hand if you have ever built a system with the Model-View-(Whatever) pattern.
    Raise your hand if you have ever built a system with the Chain of Responsibility, Repository+Unit of Work, Observer, Mediator, Strategy and Abstract Factory patterns.

    MV* has been around since Smalltalk; it is probably the most well known and understood pattern and it serves as a “yeah. I can do that” pattern for project teams that are trying to avoid filling out their entire roster with senior developers.

    I also think that it has become the Architect’s equivalent of Visual BASIC. My philosophy when evaluating developers is that there is nothing inherently wrong with Visual BASIC. I know some very competent, professional Visual BASIC developers that I would love to have on any of my project teams. But what does the ‘B’ in BASIC stand for, again? It stands for Beginner’s. “Why is a professional developer working in the beginner’s language?” is a very appropriate question to ask. But if you don’t personally know one, you have to take a very cautious approach to vetting VB developers because it’s easy for a beginner to talk the talk…and I don’t want a beginner on my team. The same goes for MVC. It is the “Beginner’s Architectural Pattern.”

    The MV* pattern itself (with whatever you wish to fill your star with) essentially breaks down to 3 primary moving parts and many junior to mid level developers that don’t have the experience, education, or intelligence to design a robust system from the foundation up can at least drop MVFoo as an overarching pattern and create something that is deliverable. That is not to say that what they deliver will be correct, appropriate for the situation, or maintainable by the time it is shoe horned; bubble gummed; and duct taped to make it fit approximate facts of their problem domain that they (or their management) wished to sweep under the rug.

    That does not mean it is never appropriate though. In my experience, it works very well for small components of a system that communicate with each other through a messaging infrastructure. It is very effective for creating thin client UI layers that sit atop a service layer that is designed with “something else.” It doesn’t work well when it is used as an excuse for not decomposing your system properly. I’ve seen 1k,2k,3k,+ line controllers that are obviously wrong by the simple fact that they contain that many lines of code. In these cases, it is apparent that the architectural decision to go with the default option of MVC painted a beginning architect into a corner that he didn’t know how to design out of.

    That to me is the true danger of MVC/MVVM/MVFoo.

    • Jeroen Meeus

      You understand me :)

      • PocketHoosier

        I do understand you, but I do also understand (or at least I think I understand) why MV* is so prevalent; some of it, I agree with and some of it I want no part of. The part that I do not want to be involved with is the ongoing, 30 year mission by business managers to automate the automators. Such a goal is futile because who is kidding who? You can’t develop a general “entrepreneurial” system that obsoletes the entrepreneur, but with sufficient resources you definitely could develop a management suite that would obsolete all of those middle and upper managers that think we’re overpaid typists. I think they know that and the desire to drive us down is a protectionist tactic designed to prevent us from building a robot to count their beans for them.

        But, as you said in your article (maybe not in exact terms): patterns are a means to an end. The Architect’s Triangle is axiomatic.

        Architect’s Triangle
        “Good”,”Fast”,”Cheap”, Pick 2.

        If your goals are “fast and cheap” then MVC may be your best option at the sacrifice of the long-term sustainability of the system…and that’s fine. It’s to the customers to decide which systems will constitute their flagship software. But they don’t understand software (unless they’re a software company, maybe). It is on us to understand enough of their business needs to *help*(not take over) shepherd them into allocating their resources in the areas of software that will give them the most bang for their budget dollars. “Maximum Quality” is not a universal goal.

        One universal truth is that you cannot model and design the universe. At some point near the boundaries of your problem domain, you must stop designing or you will never deliver a product. You also have to make economical decisions on where in the architecture you will focus your attention and sometimes budgets and timelines don’t allow you to produce an academically correct solution. This understanding is what I feel is most lacking among development professionals; this is a business. I’m in business to make money. I make money by making customers happy and spending more money than a customer has to spend or delivering late makes customers unhappy. Ergo, spending more time and budget designing areas of the system that customers don’t care about is bad for business.

        The MV* flavor that was the easiest to use with customers was MVP. I would never call it Model View Presenter, but would use the terminology that all businessmen understand: Minimum.Viable.Product. In most cases, that’s what you are building with MV*. It gets something up “fast and cheap” so the business has partially working software that will make them money while you replace it with “good.” That’s good for business for everybody.

  • http://harikt.com/ Hari K T

    Paul,

    You missed my comment just above ;) .

  • pbouzakis

    Definitely agree with some of the statements above. Let’s not confuse MVC with design patterns w/ singleton, factory, etc.

    If your main point is to be a code monkey and think you are doing your job because you use the Decorator Pattern created by an Abstract Factory which was a plugin for your favorite MVC framework, then yes you are doing it wrong.

    At the same time, these are best practices for a reason. Even if you don’t want to use “MVC” you are probably going to do something very very similar. You will separate your concerns. MVC is abstract and there are many contexts and ways to implement it.

    To me, too many developers concentrate on the implementations rather than the actual pattern and when they are appropriate.

    If you are just writing a prototype, you can probably just hack away. For the rest of us, probably not a bad idea to understand these patterns and architectures so we leverage the mistakes and lessons learned from our predecessors.