Question

This question is specific to zf2 but I think this may also be a more general MVC question.

I created a column in my mysql DB which my application uses (lets say a user entity's description field) that is stored as a string. This field is optional and if the value was never changed by the program it is set to null.

I'm using zf2's table gateway so I have a model for this table.

Right now in my view template I check if the value is null and if it is display this to the user as "Not entered", but I was wondering if my I should do this in the model? For example in the model for this table I check if the value is null and change it to "Not Entered" so this way I could remove this logic from my template. The downside though would be that when I use the model to do an update of the table I may have to convert back to null.

I do it that way now for timestamps. I convert timestamps in my model to date strings before they get the view layer (maybe I should be converting the timestamps in my view templates instead?)

Do most zf2 developers just take care of this in the view templates or is there some advantage to doing this in the model I'm not seeing.

Was it helpful?

Solution

For example in the model for this table I check if the value is null and change it to "Not Entered

This is typically view constrained logic. Now you want to render "Not Entered", perhaps in another UI you want to display something else. Keep in mind it is not per se a bad idea to have logic in your view, it should only be view related. Check if a value available and act accordingly is perfectly viable view logic.

I do it that way now for timestamps. I convert timestamps in my model to date strings before they get the view layer (maybe I should be converting the timestamps in my view templates instead?)

Keep the model layer domain driven: use semantics to describe your domain. If you deal with timestamps, PHP's DateTime class is a very good solution. Use these objects or if not present, set it to null. This way you keep your model layer together.

A perfect viable signature for the timestamp is:

public function setTimestamp(DateTime $timestamp = null) {
    //
}

This way you enforce the variable to be a valid DateTime instance or you just allow null.

Your view layer can contain logic such as:

<?php if ($object->getTimestamp() !== null): ?>
    <p><?= $object->getTimestamp()->format('c')?></p>
<?php endif ?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top