I am new to the world of coding and am having a hard time understanding what MVC is and how I can apply it to PHP. At the risk of this question being closed I have scoured the web for numerous articles however none of them explain them explain MVC in a way I can understand.
For example, I came across the article at Coding Horror – http://www.codinghorror.com/blog/2008/05/understanding-model-view-controller.html however I am unsure how I can apply it to PHP. I apologise for posting an ambiguous question earlier however I hope this question is more direct.
Let’s take a look at example that will hopefully help me understand. The objective is a user must complete a registration form that will have the details recorded in a database.
I currently have the following files
– a PHP file (i.e. with the extension PHP) with XHTML markup – There is no code in here as yet except XHTML mark-up
– a CSS file
I have also have a MySQL database
- How would develop the registration form using MVC?
- What files should I have?
- What folder structures would I have?
I am not looking for actual code but an example of how I would develop a MVC application.
Folder structures are irrelevant. The main point of MVC is a logical separation.
You should have one model, which takes care of your data. This includes storing data in the database (or elsewhere), validating the integrity of data (i.e. make sure all values are as you want them, no strings in fields where you want numbers etc.) and retrieving data.
You should have a view, which just presents data to the user or gives the user an interface to interact with your application. That’s typically your files containing (X)HTML.
Then you need a controller that makes these two things work together. The controller is responsible for receiving user requests, deciding what to do with them and rendering an appropriate view in response.
These three parts can be realized in many ways (classes, objects, functions, files), as long as the logical separation is preserved. The logical separation makes things easier in the long run, since you always keep the core of the application (models) separate from the presentation (views) and can dynamically combine both in many ways (using controllers).
The typical logical flow for a form would be:
Visualized it’s something like this:
I suggest you start playing around with an existing MVC framework to get the feel for it.