The time has come for me to understand MVC, so that’s what I’m trying to do; and I’m having trouble getting what a model is supposed to do. According to Wikipedia, a model:
The model manages the behaviour and data of the application domain,
responds to requests for information about its state (usually from the
view), and responds to instructions to change state (usually from the
controller). In event-driven systems, the model notifies observers
(usually views) when the information changes so that they can react.
And in CakePHP, you supposedly set up a model in this very simple way:
<?php
class Posts extends AppModel {
var $name = 'Posts';
}
?>
So if I wanted, for example, the last 10 posts in my database, I would create a controller which would look something like this:
<?php
class PostsController {
function retrieve_latest($number = 10) {
$posts = $this->Users->find(array(
'fields' => '*',
'order' => 'posts.post_id DESC',
'limit' => $number,
'page' => '1',
'conditions' => array('posts.post_display == 1')
));
$this->set('posts', $posts);
}
}
?>
And this guy would pass a variable called posts to my view, which would then render it accordingly. The thing is, isn’t my model supposed to do anything else?, because if its as simple as this, there would be no point for custom models at all, I mean, its just an empty extension to the model class.
This “empty extension to the model class” already does a lot of things: It hooks up to the database and does all the minute handling of retrieving and saving data. It is supposed to do a lot more though, including holding validation rules which are enforced anytime you’re writing to the database, any data massaging necessary in before/after filters and any other custom business logic you need in your application. Models are for storing your central business data logic, so anything that’s not presentation or input/output related but essentially models the core logic of your application. Just because the basics are simple to set up doesn’t mean there isn’t more to them.