I’m new to MVC. You have been warned…
I have User model that can return a MySQL result resource to a controller. The controller passes the MySQL resource over to the view to display. Is it acceptable to print the query results in the view, using a database result fetching function?
<?php while($row = some_fetching_function($database_result_resource): ?>
<tr>
<td><?=$row['Username']?></td>
...etc
</tr>
<?php endwhile; ?>
That doesn’t look right to me. It’s tightly coupled, right? The model must return some type of database resource, and the view has to loop through it using some type of database fetching method. Can that be decoupled without looping through the results twice? I’m thinking you would have to loop through the results in the model to create an array of the results, and then again in the view.
In summary:
- Can the view display a database result resource, while adhering to the MVC design pattern?
- Is it possible to avoid looping through the data twice, while avoiding tight coupling to a database?
If you abstract away the database part of the code I think it’s acceptable. For example, you could provide a “rowset” which can be iterated (implement Iterable interface or something). Behind the scenes, this object could contain a database result and use the fetching function.
Basically the idea is that your view deals with a generic looking rowset which doesn’t imply it’s coming from a database or any other source, and that way you reduce the coupling.