phpmodel-view-controllerviewzend-framework2

Separate HTML from Recursive PHP function(s)


I'm trying to separate the HTML elements from the PHP code within Zend Framework 2, but I have no clue how to solve this problem. I'm currently echoing those HTML elements, which does the job. However, there must be a way to separate the HTML from the PHP, rather than echoing the HTML elements.

Currently, I have created a view helper that allows me to generate this tree map for other modules as well, since they will also use this feature, provided that this helper is given a tree map. The categoryTreeMap contains a tree map of category (Doctrine 2 ORM) objects.

This is what I've got so far:

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;

class CategoryTreeMapHelper extends AbstractHelper
{
    public function __invoke($categoryTreeMap)
    {
        echo "<ol class=\"sortable\">";
        foreach ($categoryTreeMap as $category) {
            $this->showCategories($category);
        }
        echo "</ol>";
    }

    public function showCategories($category)
    {
        echo "<li><div>" . $category->name . "</div>";
        if (isset($category->childs)) {
            echo "<ol>";
            foreach ($category->childs as $child_category) {
                $this->showCategories($child_category);
            }
            echo "</ol>";
        }
        echo "</li>";
    }
}

Any suggestions on how to solve this, by separating the HTML from the PHP echo's?


Solution

  • If your helper solely consist of those two methods, you can replicate the functionality in templates by making use of the partial helper

    Create a partial for your treemap container

    // view/partial-treemap.phtml
    <ol class="sortable">
        <?php foreach ($this->categoryTreeMap as $category) :
            echo $this->partial('partial-category', array('category' => $category));
         endforeach; ?>
    </ol> 
    

    Create a partial for the recursive part (which calls itself recursively for children)

    // view/partial-category.phtml
    <li>
        <div><?php echo $category->name; ?></div>
        <?php if (isset($category->childs)) : ?>
        <ol>
            <?php foreach ($category->childs as $child_category) :
                echo $this->partial('partial-category', array('category' => $child_category));
            endforeach; ?>
        </ol>
        <?php endif; ?>
    </li>
    

    Then in your controller action view you only need one line

    <?php echo $this->partial('partial-treemap', array('categoryTreeMap' => $categoryTreeMap)); ?>