I am learning a MVC structure. I studied on basic example by creating class from http://www.sitepoint.com/the-mvc-pattern-and-php-1/. Now I want to develop small application where array is defined in model and displayed in HTML page. Can any give me small example so that i will understand better flow.Thanks in advance.
1 Answer
as Wilson says, you need to pass data from your model into your templates with your controller. But Ill try to explain the process.
You need to remember that your model (database and associated functions) doesn't know about, or care about your views. Its the controllers job to get what the template needs from the model, sort it out, manipulate it if needed and then pass it to the template.
The idea behind this is that your model can change, or your view can change without effecting the other. The controller would take up the strain. This also means that you can use your template for other things (like a report template for instance), or you can use your model methods for other things.
This image shows how the relationships work:
So, in your controller you might have something like this:
// use your database repository to get the data (run your query from your model code)
// ....
$databaseManager = new DBManage();
$data = $databaseManager->getSomeDataFromTheDatabase();
$processed_data = $this->doSomethingWithThisData($data);
// render the template in whatever way you do, passing in the data with it
return $this->render('index.php', array(
'data' => $processed_data
));
// ....
The model might contain:
// this could be anything from a full ORM entity model, or a simple class containing some methods to access data.
class DBManage {
// ....
public function getSomeDataFromTheDatabase() {
$query = 'select * from cars';
return $this->execute($query)->fetchData();
}
// ....
}
Then finally in your view:
<table>
<?php foreach($data as $row): ?>
<tr>
<td><?php echo $row[0] ?></td><td><?php echo $row[1] ?></td>
</tr>
<?php endforeach; ?>
</table>
Now how you go about rendering depends on the rest of your application. If you dont already have a solution for that it might be worth looking into a simple ready made framework or if youre comfortable, importing a framework component such as Symfony's awesome templating module.
