Search code examples
phpmodel-view-controllerzend-frameworkzend-route

Where is the best place to generate routes in an MVC-application?


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?


Solution

  • 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.