ZF2 widgets/views in layout

我与影子孤独终老i 提交于 2020-01-17 14:00:06

问题


I am working on a website where I need a "widget" like view in my layout of Zend Framework 2. the widget should show the operational status of the server (this is done).

(Correct me if this is bad MVC style) I have build a controller with the

function viewStatusAction(){ 
   ... 
   return $viewModel(array($vars))
}

then i want to use a viewHelper to get the status of the action. This is where I'm stuck. I know how to create the viewHelper, but not where to start to get the returned view from the controller action. So how do i do this?


回答1:


You can use the Zend\Mvc\Controller\Plugin\Forward controller plugin to dispatch another controller action from within another.

The docs say

Occasionally, you may want to dispatch additional controllers from within the matched controller – for instance, you might use this approach to build up “widgetized” content. The Forward plugin helps enable this.

This is useful if you have already have these actions but would like to combine them with others to build an aggregated view.

use Zend\View\Model\ViewModel;

class AdminController extends AbstractActionController 
{
    public function adminDashboardAction()
    {
        $view = new ViewModel();
        $view->setTemplate('admin/admin/dashboard');

        //..
        $serverStatsWidget = $this->forward()->dispatch('ServiceModule\Controller\Server', array(
            'action' => 'status',
            'foo' => 'bar',
        ));
        if ($serverStatsWidget instanceof ViewModel) {

            $view->addChild($serverStatsWidget, 'serviceStats');
        }

        return $view;
    }

As $serverStatsWidget is the result of the dispatched controller, you can then add it to the 'main' view as a child and render the result just by using echo.

// admin/admin/dashboard.phtml
echo $this->serviceStats;



回答2:


Here is what i did. This should also be the right way to do it

in module.php

public function getViewHelperConfig()
{
    return array(
        'factories' => array(
            'statusWidget' => function ($sm) {
                -- some service handling --
                $statusWidget = new statusWidget($service);
                return $statusWidget;
            }
        )
    );
}

then i created a viewHelper in operationalStatus\View\Helper

<?php
namespace operationalStatus\View\Helper;

use Zend\View\Helper\AbstractHelper;

class statusWidget extends AbstractHelper
{

    public function __construct($service){
        $this->service = $service
    }

    public function __invoke()
    {
        -- collect data from the service --

        return $this->getView()->render('operational-status/widget/status', array('operation' => $status));
    }

}


来源:https://stackoverflow.com/questions/25533751/zf2-widgets-views-in-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!