I’m programming a Ticket Management system with CodeIgniter and I have an MVC dilemma whether conditional coloring should go in the Model or in the View?
The view should display all tickets in a grid.
Let’s say the tickets have deadline datetime. When there is less than an hour left, the ticket should be colored in Red, when there are between one and six hours left, the ticket should be colored in Yellow, and when there are more than six hours left, the ticket should be colored Green.
So, should the view contain logic like
foreach($tickets as $ticket):
if($hours_left >= 6): <span class="green">...</span>
else if($hours_left >= 1 and $hours_left < 6) <span class="yellow">...</span>
if($hours_left < 1): <span class="red">...</span>
or should the color be retrieved as a property from the model?
foreach($tickets as $ticket):
<span class="<?php echo $ticket->color; ?>">...</span>
In the first case, the view gets logic and it is not “dumb” anymore. Even worse, if this needs to be applied in multiple views, I need to repeat the code which is difficult to maintain, for example if I wanted to add a “blue” color.
In the second case, I will need to embed display logic within the model, which is also against MVC principles.
Where should color logic be put?
UPDATE: Added helper code example
I would write a helper function that you can call in the view to add the correct CSS.
This way you are not messing with the model structure, for example if you have a field in the database called
ticket_expires, you will still be able to use this value else where if required.To make a helper function;
Create a file in /application/helpers called *ticket_helper.php*
In this file put something like;
Just remember to either load this helper when you need it, or autoload it.
So in you view;