Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I'm using the Yii Framework which is an MVC php framework that is pretty similar to your standard web-based MVC framework. I want to display the related data from a many-to-many table as a list of strings in my view.

Assuming a table schema like:

tag { id, name }
post { id, title, content, date }
post_tag { post_id, tag_id }

A post will display like:

Date: 9/27/2012 
Title: Some Title
Content: blah blah blah...
Tags: Smart Funny Cool Informative

I can achieve this by doing something like this in my Post view:

<?php
  echo join(' ',
           array_map(function($tag) { return $tag->name; }, $model->tags));
?>

(where $model->tags is an array of Tag objects associated with my model)

My questions are:

  1. Is this amount of code/logic okay in the view? (Personally I think I'd rather just reference a property or call a single function.)
  2. If not, where should this code live? In the model? the controller? a helper?

Potentially I may want to use in in other views as well. Ultimately I think its purely a display issue which would make me think it should be in the view, but then I have to repeat the code in any view I want to use it in.

share|improve this question

3 Answers 3

If it is a function specifically oriented at structuring output, I would put it into a view helper.

However if the code touches some logic, it should move to a controller or model or way down to your business logic classes, depending on what is your code doing or what is you structure.

I personally would put your code in a view helper.

share|improve this answer

Is this amount of code/logic okay in the view? (Personally I think I'd rather just reference a property or call a single function.)

For clean separation of concerns in MVC design, you better move all calculation from your views to controller or service layer. Thus, code should live in your controller, assigned to a new property of your viewmodel or dto.

share|improve this answer

I think would be a fine thing to put into a view or view-helper. My rationale is that you're passed all the data and printing out the array with a space in-between is part of the view. If you were to implement another set of views for mobile or something, it could possibly be implemented differently, and if you used a web-service you'd definitely do it differently.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.