1

I have a nested array that is compiled via the model in a CakePHP request. The array can be nested at a variable depth, and the content is to be returned to the user.

Currently the looping and rendering process for this array is completed using a function in the View element of the request. This function is first called at the base array's depth, and repeated for any array element that has further array children. eg.

function print_depth($elements) {
  foreach($elements as $element) {
    echo $element['title'];

    if($element['children']) {
      print_depth($element['children']);
    }
  }
}

print_depth($elements);

With this process, I can print out all levels of the array, whilst still keeping the markup flexibility within the view (hence, it is skinnable), but I imagine this is the incorrect location for the function that handles this.

Is there a more MVC-valid process for this operation?

2 Answers 2

2

From an MVC point of view it's probably right where it belongs, since it's the views responsibility to prepare data for visual representation. However for a more DRY approach, you could implement this functionality in a helper.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but wouldn't this be invalid simply because the function would be existing within the function that calls the view file? I know PHP will allow this, but thought it was frowning upon.
Generally I wouldn't call it invalid, it's just a little "dirty" because it could easily violate the DRY principle when needed in multiple views, and because it will become a globally accessible function, which some people might consider a violation of the MVC principle since it makes "internal" view functionality available outside of the view, however a helper would be available outside of the view too, so I'd say that's kind of splitting hairs. Anyways, for a clean approach you should use a helper, that's the recommended way to go.
1

Create a helper instead of putting a single function in the view code.

What you do sounds like rendering a tree, there is already a tree helper out there.

https://github.com/CakeDC/utils/blob/master/View/Helper/TreeHelper.php

Comments

Your Answer

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.