Well, the biggest issue is that MVC doesn't actually specify implementation details. It stats what the model is used for and not specifics on how it works. Technically any 'model' is correct (provided it is a model and not a controller :P )
Here's a trivial example, but again, any implementation details I've included here are irrelevant in terms of MVC and are there for ease of demonstration only.
PHP Code:
<?php
class UserModel extends Model {
public function create($registrationDetails) {
//This is included as an example of the kind of logic people erroneously put in controllers
if ($this->validate($registrationDetails)) {
$user = new User;
$user->populate($registrationDetails);
$this->save($user);
}
}
protected function validate($registrationDetails) {
if ($this->findByUsername($registrationDetails['username'])) {
return false;
}
else {
//check email address, validate other form fields...
}
}
protected function save(User $user) {
//take the user object and insert it into the DB
}
protected function findByUsername($name) {
//... fetch a User object with username of $name or return null.
}
public function find($criteria) {
//query the database based on criteria. This will be called by the view, not the controller.
}
}
?>
Essentially the goal is just to move the logic out of the controller. All the controller should be doing is passing the user-supplied details to the model.
An interesting sub-topic is, should models have a state? (e.g. should they be working based around a specific User object which is stored as a property of the model) In my opinion, no, but it does make it easier in some cases.
Bookmarks