PHP MVC Principles
- by George
I'm not using an off-the-shelf framework and don't particularly want to (nor d I want to go into the reasons why...). Anyway, onto my question(s), I hope it make sense....
I'm trying to get my head around what should go in the model and what should go in the controller. Originally I had the impression that a model class should represent an actual object (eg - a car from the cars table of a database) and model properties should mirror the database fields. However I'm now getting the feeling that I've got the wrong idea - should an instance of a model class represent an actual item, or should it contain a number of methods for doing stuff - sometimes to one car or sometimes to multiple cars based on my example earlier.
For example I want to get all the cars from a the database and show them in the view. Am I right in think it should be along the lines of this?
Controller File
function list() {
$cars = $this->model->get_all();
$this->view->add($cars);
$this->view->render('cars-list');
}
Model File
function get_all() {
// Use a database interaction class that I've written
$cars = Database::select();
return $cars;
}
Now, if the car had a "status" field that was stored as an integer in the database and I wanted to change that to a string, where should that be done? By looping the SQL results array in the get_all() method in the model?
Also, where should form validation live? I have written a validation class that works a little like this:
$validator = new Validator();
$validator->check('field_name', 'required');
If the check fails, it adds an error message to the array in the Validator. This array of error messages would then get passed to the view. Should the use of my validator class go in model or the controller?
Thanks in advance for for any help anyone can offer. If you know of any links to a simple MVC example / open source application that deals with basic CRUD, they would be much appreciated.