Where to set Zend2 Partial View's data?

2019-08-07 06:21发布

问题:

Let's pretend I have a view being shown as:

<?php 
    echo $this->partial( 'site/testimonials/partial.phtml', array() ); 
?>
<?php

Let's say I have a table called "testimonials" and the purpose of this view is to only show the most recent testimonial in the database on another view.

Where during this process will I specify where the data must come from? Do I pass it in to $this->partial, or is there a better and more correct way to place the db query logic in the partial view? It's a view, so no logic is tied to it, but how then would I assign a "testimonial model" to it, and have it automatically grab the data from the db when displaying this view?

IN SHORT

Where do I place the logic to get the latest testimonial, if I want to avoid passing variables (such as the latest testimonial ID) to the partial view?

回答1:

For such tasks i think it is better to make view helper.

Inside Module.php class:

<?php

use Zend\View\Model\ViewModel;

public function getViewHelperConfig()
{
    return array(
        'most_recent_testimonials' => function($helperPluginManager){
            $serviceLocator = $helperPluginManager->getServiceLocator();

            $view = new ViewModel();
            $view->setTerminal(true);
            $view->setTemplate('site/testimonials/partial.phtml');

            /*
             * There you may get all data you need using $serviceLocator
             */

            // inject data into template
            $view->setVariables(array(
                ...
            );

            // render template
            $template_rendered =
                $serviceLocator ->get('viewrenderer')
                ->render($view);

            return $template_rendered;
        }
    );
}

Inside view:

<?php echo $this->most_recent_testimonials(); ?>