3

Imagine you have the following scenario:

In you application, you have several models that are "Commentable". Comments are shown in an identical manner and can thus utilize the same template. In the default view of the comments widget, the two most recent comments are shown, with a link to load remaining X comments.

The widget also have a form (i.e textarea that submits on enter-key) for adding a new comment to the model.

Given the above requirement, where is a reasonable place to generate the links that the form and load-link needs to do its work?

Should the links be generated in the view that calls the template, together with the Commentable model? i.e.

<?php
  echo $this->partial('path/to/template/comments.phtml', array (
    'add-link' => $this->url($params, $routeName),
    'load-link' => $this->url($params, $routeName),
    'comments' => $this->model->getComments()
  );

Is it, at all, acceptable to ask the Commentable for these links? I.e in the comments.phtml-template:

<div class="comments">
  <div class="loadLink">
    <a href="<?php echo $this->comments->getLoadLink() ?>">
       <?php echo sprintf('Show all %d comments', count($this->comments)); ?>
    </a>
  </div>
  <div class="container">
    <?php 
       foreach ($this->comments->getFirst(2) as $comment) {
          echo $this->partial('comment.phtml', array('comment' => $comment);
       }
    ?>      
  </div>
  <div class="addComment">
     <form action="<?php echo $this->comments->getAddLink() ?>" method="post">
       <div>
          <textarea class="autogrow" name="comment" 
                    placeholder="Write a new comment" rows="1" cols="80">
          </textarea>
       </div>
     </form>
  </div>
</div>

Since MVC advocates that the view can communicate with controllers, is route generation viewed as a way to "communicate" with a controller, even if it doesn't do so in an object-to-object manner?

Community
  • 1
  • 1
PatrikAkerstrand
  • 45,315
  • 11
  • 79
  • 94

1 Answers1

1

In an MVC application you should never ask the model to construct a link. You should add some view helper that may use the model to generate these links.

saintedlama
  • 6,838
  • 1
  • 28
  • 46
  • Yeah, that's what I'm doing at the moment. It, however, relies on `get_class($model)` to call a protected method in the view helper to generate the links for that specific model, and it just feels.. dirty and coupled. =) – PatrikAkerstrand Oct 25 '11 at 21:23
  • 2
    In case you would do it in the model the model would be coupled, if you would build the urls in the controller and set some property in the model the controllers would be coupled. When it comes to coupling always ask yourself the question: What code can be easiest replaced by a different behavior - and for me the view helper is a perfect candidate – saintedlama Oct 25 '11 at 21:27