Note: Robert C. Martin (aka Uncle Bob) explains this in a much better and humorous way in his keynote, Architecture the Lost Years. A bit long but teaches lots of good concepts.
tl;dr: Don't think and plan your app in terms of MVC. The MVC framework is just an implementation detail.
The most confusing thing about MVC is, developers tries to use all the components glued together.
Try thinking in the terms of a program, not in the terms of the framework.
Your program has a purpose. It takes some data, does things with data, and returns some data.
That way, the controller
is the delivery mechanism of your program.
- A user sends a request to your program (let's say, add a product to the shopping cart).
- The controller takes that request (product info and user info), it calls the necessary part of your program that will handle this request
$user->addToCart($product)
- Your program (
addToCart
function of the user
object in this case) does the work it's intended to do and returns a response (let's say success
)
- The controller prepares the response using the relevant
view
: eg. in the controller object $this->render($cartView('success')
This way, the controllers are decoupled from the program, and used as delivery mechanism. They don't know how your program works, they just know which part of the program need to be called for the requests.
If you want to use another framework, your app won't need a change, you will just need to write relevant controllers to call your program for requests.
Or if you want to make a desktop version, your app will stay the same, you will just need to prepare a delivery mechanism.
And the Model
. Think of it as a persistence mechanism.
In the OO way, there are objects in your program that holds the data.
class User {
//...
private $id;
private $shoppingCart;
//...
}
class Product {
//...
private $id;
//...
}
When you add a product to the shopping cart, you can add the the product::id
to the user::shoppingCart
.
And when you want to persist the data, you can use the model
part of the framework, which generally consist using an ORM, to map the classes to the database tables.
If you want to change the ORM you use, your program will stay the same, only the mapping information will change. Or if you want to avoid the databases all together, you can just write the data to plain text files, and your app will stay the same.
So, write your program first. If you programming with the 'OO' way, use plain old objects of the language. Don't think in terms of MVC at first.