2

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.

asked Sep 27, 2012 at 23:27

3 Answers 3

2

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.

answered Oct 19, 2012 at 13:31
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.)

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.

answered Sep 27, 2012 at 23:32
0

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.

answered Oct 19, 2012 at 13:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.