So, you're learning about Models, Views, and Controllers. What's the difference, how do they work with each other, and what does this have to do with your application? Let's break it down and simplify the MVC framework.
The Model is responsible for holding all the logic that applies to a specific Class in the application. The Model also accesses information from the database and sends it to the Controller to route.
The Controller is responsible for routing information from the Model to the View, then from the View to the browser to display the contents for the end user. The Controller will have all the methods on any actions (Create, Read, Update, Delete, or other) that apply to the Class.
The View is responsible for taking the data from the Controller and defines what is displayed on the client side. All frontend code will be housed in Views for all the actions in a specific Class.
When we apply all this information to the above scenario, the flow within the framework would proceed as:
- The browser requests for the "/users" URL
- The application routes the "/users" URL to the action that is housed in the Controller
- The specified action asks the User Model to pull information on that class from the Database
- The User Model pulls the information from the Database
- The User Model returns the information to the Controller
- the Controller sends a request to the View based on the original action
- The View renders the action's webpage as HTML
- The Controller passes the HTML to the browser
Ok great, now we understand the MVC framework! But how do we make it work and do things for your application?
In the Controller subsection, we talked about how it holds all the methods for any actions that apply to that class. When we have a Class in our application, let's say, a User Class, we want to be able to obtain or manipulate the data in the database in ways such as creating a new user, viewing a specific user, deleting a user, and so forth. When a request is made to perform that kind of functionality, the Controller uses RESTful conventions and looks to the Routes file to help map to the method that matches what the browser is requesting.
So REST, simplified, is commands performed, such as our aforementioned CRUD actions.
In the diagram above, we see the HTTP verb hitting a specific URL path and being routed to a specific method, or action, within the Controller to render and display the information within the View.
Simplifying our HTTP verbs:
- GET: simply retrieves information, does not manipulate any data within the database
- POST: creates new data based on the information enclosed in the request
- PATCH: updates existing data with the information enclosed in the request
- DELETE: deletes the data enclosed in the request
Now that we have a better understanding and high-level overview of MVC and REST, we can use the MVC framework and the RESTful design pattern in conjunction to create a badass application! Happy coding!