Php – where to put which code in MVC model

mvcPHP

I recently picked up learning PHP and MySQL and I am trying to build a small usersystem as a coding exercise. While learning to use classes and functions, I also stumbled upon the MVC model and would like to implement the model in my code.

Is the following approach correct MVC?

  • index.php, message.php, user.php are all a bunch of controllers. They start a model, collect $_GET, $_POST and $_SESSION user data and passes that on to the model. They may collect info from the model and pass it on to the views.

  • the user class, message class, etc. … are all parts of the model. They validate the data that the controller gives them, do the actual database stuff and return data to the controller and the view.

  • the views are puzzled together by the controller. They mainly echo data from the model & the controller and include html files.

My main concern is how the view displays data from the model. Is it better to go through the controller or should I directly get it from the method whenever I can?

Best Answer

Your understanding is correct. Keep in mind that different frameworks use different approaches, so something which would for instance apply to Laravel won't necessarily apply to, say, Symfony.

This is especially true when it comes to deciding where the logic goes: some frameworks use models as basic objects containing data, but practically no logic by themselves. Other frameworks encourage you to move some logic from the controllers to the models.

A few comments:

  • Why is your controller called index.php? Usually, the application has several controllers with the names which indicate their purpose. For instance, an e-commerce website can have a products.php file which contains the controller logic handling http://example.com/products/... requests, customers.php file for customer-related stuff, cart.php for you guess what, etc.

    Unless you have separate directories for each of them, such as /products/index.php, customers/index.php and cart/index.php, you are putting all the logic in the same file. As a consequence, even if the file is currently small, it will grow through time, and become very difficult to maintain.

  • While doing input validation inside a controller is a perfectly valid approach, some frameworks move the validation logic from the controller to (1) the model and (2) the framework itself. I don't know PHP frameworks, so I'll give an example of ASP.NET MVC: usually, properties within the models have specific attributes which indicate how should they be validated. Then, basic validation logic is applied by the framework itself during the mapping.

Related Topic