Php – MVC with Post/Redirect/Get

mvcPHP

I have a question in mind for the MVC pattern for a long time now. When using the Post/Redirect/Get principle then it doesn't make sense to use ONE model in the sense of MVC, right? Why should I modify the data in the model if I don't use it anymore? Am I missing something?

So I need one model for the actions in the controller and one with the data for the view?

My current pattern:

controller

-> call and init model used for actions

-> handle actions using the action model, if an action has been executed, use P/R/G to reload

-> call and init model used for the view

-> call view with template and pass view model

The point is, I don't want to load all the data for the view if I possibly don't need it due to the redirect. Or am I just caring about that too much?

Best Answer

In MVC it's very uncommon to have a single model or controller. It is however common to have one or very few view "flavors" which all render templates differently.

Each controller should have a single purpose, whether it's routing, or applying business logic to a model. You should route the request to the appropriate controller for each model, ideally separating POST and GET handling into separate functions. If POST, save and redirect. If GET, display the view.

  • Model = Structured data. Throws validation exceptions. May contain storage logic.
  • Controller = Routing and business logic. Works on models directly or through another controller. Assigns presentation data to views, such as models, headers, sub-views, etc. Dies gracefully upon errors.
  • View = Presentation. Uses whatever it's given in a read-only way. Should produce no errors.

If you're asking whether it's correct to initialize the model for each type of request, the answer is probably yes, unless your POST validation is incredibly simple and is allowed to clobber existing records.

Related Topic