MVC in simpler terms or the structure of a modern web-application
MVC is one of the most controversial terms in the PHP world.
Whereas it's really simple as long as you get the main principle: the Model is 90% of your application.
The Model
Thanks to the first generation frameworks, the Model is mostly associated with a database layer. Which is obviously wrong. The Model is whole your application actually, just without the interface. So it includes a database layer but also all the logic that provides the exact data to be returned to the client or methods to manipulate the data in the database.
I do realise that this concept is hard to grasp at first, but it will become much clearer the day you will need to create a command-line version of some action usually taken through the web-interface. Such as trivial task as creating a new user for example. Immediately it will become apparent, that both the Controller (the web interface) and the Command (the command line interface) are actually extremely thin layers, just interfaces that convey your actions to the Model.
No kidding, this is a real good test for your controllers. Just try to create a command line interface for creating the new user and see, whether you will need any code borrowed from the controller. If so -your Controller is fat and this code should be moved into the model.
Just a couple such cases and for the rest of your life you will stop making fat controllers that take up some of the responsibilities from the Model and thus make it hard to call the same functionality through any other interface.
So in a nutshell, your Model should be able to perform any task your application is supposed to do, no matter through which interface it is called.
Given the Model is up to 90% of your application, it is not unnaturally that itself it is often divided into different parts depends on the different areas of responsibility.
The Entity or a Data Mapper
This is what most of time is mistakenly taken for the Model - the basic mapping from a database table to a data object, which implements basic data manipulation methods also called CRUD.
The Repository
This is mostly a collection of complex SQL queries, that do not fit for the Entity. The source of any data your application may be in the need for.
The Helper
This is the place where the code from your fat controller should go. Like Repository, this is a general purpose script but unlike Repository it doesn't run any SQL query (calling either an entity or a repository for this), performing any data preparation necessary. For example if the data needs to be combined from different repositories, one could call corresponding methods from these repositories and then combine the data in the any fashion appropriate.
The Router
There is no R in the MVC acronym as this part is specific to the web-application only. The job of the Router is to determine which controller needs to be called to process the certain HTTP request.
The Controller
As it was mentioned above, the Controller should be a really thin layer whose the only job is to take the request parameters, send them to the Model for processing and then return some response back to the client (directly of by calling the View).
The View
A rather less important module that is called by the Controller, responsible for the HTML rendering. Obviously not used with Commands but also never used if a controller has been called through REST request, as in such a case instead of calling the View the Controller will simply encode the data into JSON format and simply return it.
The Command
As it was noted above, the Command is just a command-line interface that may duplicate some actions that usually performed by a controller, but of course could be specific to a command. Usually it is some maintenance tasks performed by a site admin through command line or via the cron job.
Related articles:
- Relative and absolute paths, in the file system and on the web server.
- PHP error reporting
- Do you abuse the null coalescing operator (and isset/empty as well)?
- Do you really need to check for both isset() and empty() at the same time?
- What's wrong with popular articles telling you that foo is faster than bar?
- Articles
- Numerical strings comparison
- How to get a single player's rank based on the score
- Why should I use prepared statements if escaping is safe?
- Operator precedence or how does 'or die()' work.
- Do generators really reduce the memory usage?
- How to make Stack Overflow a nice place
- How to debug small PHP programs
- Iterating over array getting look-ahead items along
Comments:
I was just curious what you find the most effective way to learn php and become proficient? so far I've taken an online course and am finishing working through a current book, but just curious how experts started.
Reply:
Hello Jeff!
It would say it's not how you start but rather how you progress. One doesn't become an expert from learning, which only can give you the basics. You get expertise from solving real life problems. Creating a working application and maintaining it for a long time is a must. It gives you perspective, experience, understanding. Like, when you have to add an new feature to a poorly designed application, it takes many pains and gives you a hint how to design it better. This is where theoretical knowledge helps: when it's applied to a real world problem that you feel to the bone.
What you call "repository" is actually "table gateway".
Colonel,
Thanks for the in-depth answer, so the "Model" is actually the entire application. So really, they are EVC frameworks, fundamentally?
Reply:
Hello Chris!
I wouldn't say so. A web version of MVC is a good transition of the standalone application's MVC. there, naturally would be single model, single controller and single view. However, as a web application has multiple entry points, it will have multiple models and views but the Model would remain single. Makes perfect sense to me.
You see, it's hard to draw a line between micro-EVCs in the sense you picture them - a single thread from E to C and to V. A typical Controller don't just directly call an Entity. There are many operations to perform and many other Entities or Repositories or Helpers or other Services involved. So I prefer to think of a Model as not separate Entities but as a compound that implements the entire Business logic, where Entities are just building elements, among others.
I’m confused, I think, because it sounds like you’re saying a Model is not the Entity? I say that because it sounds like your saying a Entity, say User, should be able to create itself?
I am most likely completely wrong, but the Repository is where I thought you would create/get the User entity. However saying that outloud then makes me question wha the heck a model even is. Perhaps its perpetrated by Laravel (which I think is much more difficult to grasp than Symfony for some reason) making it seem like a model is an entity...
Reply:
Hello Chris!
This is a very interesting question, the kind of question I crave for.
First of all, I see two questions here, so let me answer in order.
Regarding Laravel, it is using an outdated naming convention, calling its Entities Models. Many years ago it was thought that the whole application's business logic is divided into separate Models (these, in turn, related to tables in DB). For example, it was thought that a User Controller must call a User Model. But this convention was proven wrong, both from the practical and theoretical points of view. But Laravel is still following it, albeit only in naming. So don't be fooled by it: there is just one Model in the application, the whole set of code that implements entire Business logic of the site.
Symfony doesn't go this way, calling its data classes linked to database tables Entities, not Models, hence no confusion at all.
Now to the actual question of who is creating an Entity. When I wrote this article, I had only one approach in mind, namely the ORM-based approach, which is used in all modern frameworks. In it, an Entity is a data class mapped from a database table. However, it is actually two approaches, two main methods to implement an ORM: Data Mapper and Active Record. Their main difference is exactly in the methods that can read or save an Entity:
Hope it is a bit clearer now. Please comment, if you still have any questions!
Hi!
What's your take on Laravel's MVC implementation? As for Eloquent, adding query scopes or mutators (to name a few) kind of makes sense (i.e any database related operations). But I've always been confused if it's okay to put business logic into Eloquent models.
If I ever wanted an API that looks like...
Thanks a bunch!
Wow i'm kind of confused know, it seems that everything i've learned so far about MVC its a LIE !!! DAMN YOU UDEMY !!!
hey if it's not too much to ask, can you link to a good resource on "real" MVC, maybe a book or something.
thank you for the last reply.
Reply:
Don't blame udemy too much (though they are infamously known for the bad quality). I said "ideally" because in reality sometimes it's hard draw a line between MVC components. And the form validation is too close to Controller. But imagine we are doing a command-line import of bulk data which we have to validate as well? Hwere it will be apparent that validation ruless must be defined anywhere but in the Controller.
I don't know any good book but I would strongly suggest to learn Symfony, as it encourages and even enforces good practices and the separation of different MVC components.
so for example , the validation process of a form should be in the model?
Reply:
Hello!
Thank you for the interesting question!
Ideally, validation rules must be written the Model, and Controller must inject them into the form validation routine. While the validation itself should be performed in the Controller, as its job is to process all HTTP requests, including forms.
I got it.
Thank you lot!
Thank you for the article! I'm starting of with PHP and for my current project I'm using CodeIgniter. So, I have some doubts about model and entity/data mapper.
By default, CI doesn't have an entity or data mapper, so I ended up creating my CRUD within the model. Is that bad? What is your suggestion when I chosen framework only have a model?
Thank you a lot, Castle
Reply:
Hello Castle!
Thank you for the really good question!
We can roughly assume your "model" as a sort of a mix between an entity and a repository. There is nothing wrong with it.
Just keep in mind that the real model is not limited to just a database mapping (and so most of "models" that are only doing so are mis-named). I don't know if it's possible to use helpers with CI, but in case you want a canonical model, that encapsulates all the business logic by definition, you'd need some sort of a class that would implement a business logic which is not covered by your "model".
Feel free to ask if you have any other questions!
Thanks for this concise and useful explaination :)
Nice Article Thx! us neophytes need this kind of enthusiasm towards hard to comprehend listeners
i am a robot