Hey gang,

Previously I have written tutorials on PHP OOP (PHP Object Oriented Programming). I thought I would take the time to cover a design pattern that I use all the time. It is called Model View Control, or MVC for short. Model View control is a powerful way to structure your code. I have read several ways to implement this pattern I will describe how I do it.

First lets explain what Model View Control is. MVC is much like an n-tier in many ways. But it is different as you will read here. In a MVC pattern the Model is your data layer(scripts) the View is your interface layer(scripts) and the control is your logic layer(scripts).

Each layer can talk to the others. A good example would be this scenario: You have a web application that that uses a database. We will call it a classified ads application. Now in classified ads you need to store the ad, retrieve it, display it, and allow for communications between the ad submitter and the ad viewer. We will assume that we are using a database for the storing of ad data.

All database scripting would be kept in a file or directory.
This would be our model.

The scripts that make the web forms and display the ads are kept separate from the database scripts. This would be our view.

Now any validation we need to do on user submitted form values and email scripts could be kept in a separate file or directory. This is our control. (I also use the control to decide if the values need to be in the model or view).

By keeping things separate our maintenance is much easier in the future. All of our sql queries and logic are in one place. All of our markup that is dynamically generated is in one place. All of our validating, email, and other business logic is in one place. Now what makes MVC different from n-tier is the fact that each layer can talk to any layer. In n-tier the view never talks to the model directly. There is a required middle ware that facilitates the communications.

Now MVC does not have to be Object Oriented code. See here.

http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html

MVC is not the solution to every problem but it is useful to structure your code. If you are anything like me, you have looked at your code and thought, there has to be a better way to organize this. If so, MVC might help. If you are not into OOP (Classes, methods, and stuff of this nature) I recommend writing your code in collections of functions. When you do get OOP you will have a much easier time updating your code. You will also save on the amount of code you need to write.

So to conclude. MVC is a way to structure your code. In OOP this is very powerful and saves hours of time coding. However this could be very useful in procedural design as well. Please post any comments here.