MVC with one controller class?

I am learning MVC patterns, in particular with php, and have read some great lessons. I managed to get a basic stricture that works. Just for fun, I started experimenting with how controllers, models and views interact, and as a result, one controller class appeared that creates a model / view depending on the requested page. So I just create an instance of this controller basically index.php and pass url values ​​to it. For example, "mysite / blog / recent" will include the controller (and instantiate) the file "models / blog / recent.php" containing the model and the corresponding view in the views folder. My question is, is there any advantage to having the actual controller classes for each section of the website, rather than just splitting the models into different folders (like a β€œblog”) and loading them with one controller class?

+4
source share
2 answers

There is a certain point where decision making regarding MVC becomes a little less sparse and dry. For a very small (and simple) site, you may need only one controller that will do all your work for you, pulling data from models and creating views. You can, of course, create your MVC architecture so that all models and views are created by one controller, but, of course, this quickly falls apart as soon as you get to the site even with remote complexity.

My recommendation is to make your controllers conceptually separate, just as you could design an application in a modular way. I would have a BlogController with all my blogs and page service, ContactController, PortfolioController, all inheriting from the main PageController, to make sure that when the complexity of these different parts of my site expanded, I could support them without a big ol 'SoupController.

+2
source

As long as you use the MVC style and get in the habit of creating classes for things that can be organized as objects (tire.wheel.spoke), then you'll be fine.

Start small - Rome was not built in one day. You will have your first controller, perhaps when you add additional functions, you will add one more. Ive always liked the idea of ​​writing an API that calls your controllers from the very beginning, as many modern websites ultimately have to do this anyway, and this from the very beginning forces you to organize your controllers and simplify the structure of commands.

Good luck

+1
source

Source: https://habr.com/ru/post/1490082/


All Articles