Hi, I get data from Model (an array with data) and I need to display with a specific format. I need to iterate over the array, format the data and then display it. Where should I format data to display? In Model, Controller or View? Thank you.
Iteration over an array and displaying the data is done in the view. Therefore I would also do the formatting in the view. If formatting is complicated and/or requires a lot of code, put it in a helper function.
For example:
View:
<?php foreach($array as $item): ?>
<p><?php echo format_function($item); ?></p>
<?php endforeach; ?>
Helper:
function format_function($text)
{
// Do some formatting here...
return $formatted_text;
}
if your viewdata has data from different models, or has only a select part of 1 model, you could make a ViewModel, which you then could map with Automapper.
ViewModels have several advantages. They are clear to work with, unclutter your data, can add safety,...
You can do it in View.Not in model In View you can do specific operation(converting/conditions/)
If you working on a bigger project, I would suggest you to have an extra layer or class that is responsible for transforming your object (i.e. domain model object) into a data transfer object (view model object).
Otherwise apply the suggestions of doing the formatting in the view :)
The transforming could be involved with formatting strings, decimals (currency), datetimes and so on. Also transform an object graph (have a look at my example) into a flat DTO is possible.
The controller would be responsible for calling the mapping algorithm.
So in the view you do not have to iterate over references of your object. Instead you use a flat well formatted view model.
Your view will not cluttering up and looks very clean.
A tool that does this transforming job is available in the .NET world. It is called AutoMapper. Perhaps there is an equivalent in PHP.
Here is an example
This is an object model:
You could transform it into this smart view model:
The advantages of this approach:
seperation of concerns
clean view
No code duplications, i.e. formatting a datetime in each view. (Don't repeat yourself!)
The disadvantages of this approach:
- expensive for the beginning, so little projects do not profit from this approach
Do it in your View as it is responsible for the presentation.
The reason for
- not doing it the Model is that you can then render different views using the same data (otherwise you need to create different set of data),
- not doing in the controller is because it is not the Controller's responsibility