MVC for simple app [closed]

2019-09-21 11:20发布

问题:

I have been working on a simple payment calculator, which I have working correctly via a html front end and a php back end. The html passes user inputs as variables to the PHP via AJAX calls and the PHP returns a result to the html page. Now that I have it functioning as expected, I'm trying to figure out exactly how I might convert this to an MVC pattern. In my understanding, the html is the view component, the PHP, which contains all the logic for calculation, is the model, but I'm really unsure what would go in the controller? If the controller's job is to co-ordinate between the view and the model, then should I be passing my input data to the "controller" which then passes it to the php and then pass the result back via the same route? I understand this pattern in principle but this seems extraneous in this case. I have been looking into several MVC frameworks (.NET, Laravel) but really want to get a more fundamental understanding without having everything scaffolded. Any advice appreciated!

回答1:

MVC architectural pattern really is not intended for "simple apps". It tends not to be worth the effort of adding all that complexity. That's because in essence "MVC" is just a set of constraints for various layers, which you add when a large codebase becomes hard to contain.

It's not a type of magic fairy dust, that you can sprinkle on your project.

A for your "understanding" .. well .. the views really don't end up as "html". There is a bit longer post on it here, but the TL;DR version is: templates are what really handle html and views are what manage/assemble/populate the templates.

As to your main question: the responsibility of controllers are to alter the state of model layer. That's it.

It has nothing to do with scaffolding (which is a rapid-development tool) and it does not coordinate anything. As I said above: MVC is about the constraints. In the UI layer the controllers use user's input to alter the model's state and the views make a representation of the current model's state.

P.S. "Routing" is actually unrelated to MVC, because it essentially is a detail in the HTTP abstraction. You only use it to decide, which part of UI layer to "poke at".