tomfl tomfl - 4 months ago 8
PHP Question

At what point should code stop being separated in the MVC pattern?

This question is a bit theoretical. I'm building a web application using PHP and the MVC pattern. My question is : where should I stop separating the view and the controller ?




Let me illustrate this question with an example :

Let's say I want to build a system that displays the number of unread messages, if there are any. I will have 3 files : a view, a controller and a model (to make it simple, let's call them
view.php
,
controller.php
and
model.php
).


  • model.php
    is gonna get the number of unread messages from the database.

  • controller.php
    will ask and gather the information.

  • view.php
    will display this number to the user.



But if there are no unread messages, I don't want to display the number 0. So in which file should I add a condition that verifies if the number should be displayed or not ? There are two possibilities :


  • In
    view.php
    , add the following condition :



_

if ($unread_messages > 0) {
echo "<p>There are $unread_messages unread messages</p>";
}



  • In
    controller.php
    , add the following function :



_

public function countUnread() {
... // Got the data from the model
if ($unread_messages > 0) {
return "<p>There are $unread_messages unread messages</p>";
}
}


The problem with the first one is that
view.php
is only meant to display information, there shouldn't be any php code, except for retrieving information.

The problem with the second one is that the controller should only get the information, it shouldn't store any sentence or phrase : that's the view's job.




What should I do in this case ? What solutions do you think suit this problem ?

Thank you.

Answer

The problem with the first one is that view.php is only meant to display information, there shouldn't be any php code, except for retrieving information.

I don't believe this is correct. There is nothing wrong with putting logic in the View when it is directly related to what should be displayed. Based on your example:

if ($unread_messages > 0) {
    echo "<p>There are $unread_messages unread messages</p>";
} else {
    echo "<p>You have <a href=\"#\">$unread_messages unread messages</a></p>";
}

This would be perfectly acceptable in the View, because you are determining what to display based on the information received from the Model and/or Controller. Even template engines use basic control structures like this.

Edit:

Here is a similar example using Laravel:

<?php $count = Auth::user()->newThreadsCount(); ?>
@if($count > 0)
<span class="label label-danger">{!! $count !!}</span>
@endif
Comments