zf2视图策略,ViewEvent渲染器始终为null

时间:2014-01-02 09:13:06

标签: zend-framework2

我正在尝试在ZF2中实施View Strategy。

就基本设置而言,除了ViewEvent Renderer始终为null之外,一切似乎都正常工作,因此渲染器永远不会被注入到策略中,而TemplateResolver仍然会请求模板并显示以下错误。

PhpRenderer::render: Unable to render template "api/api/get"; resolver could not resolve to a file'

我甚至试图从ZF2复制代码JsonModel和JsonStrategy,但仍然得到相同的结果。 的 ViewYamlStrategy.php

public function selectRenderer(ViewEvent $e)
{
    $renderer = $e->getRenderer(); // Always return null
}

module.php

public function getServiceConfig()
{
    return ['factories' => [
        'ViewYamlRenderer' => "Namespace\Mvc\Service\ViewYamlRendererFactory",
        'ViewYamlStrategy' => "Namespace\Mvc\Service\ViewYamlStrategyFactory",
        ],
    ];
}

module.config.php

'view_manager' => [
    'strategies' => [
        'ViewYamlStrategy'
    ],
],

控制器

public function getList()
{
    return new YamlModel($data);
}

ViewYamlStrategy.php

function __construct(ViewYamlRenderer $renderer)
{
    $this->renderer = $renderer;
}
public function attach(EventManagerInterface $events, $priority = 1)
{
    $this->listeners[] = $events->attach(ViewEvent::EVENT_RENDERER, [$this, "selectRenderer"], $priority);
    $this->listeners[] = $events->attach(ViewEvent::EVENT_RESPONSE, [$this, "injectResponse"], $priority);
}

public function selectRenderer(ViewEvent $e)
{
    $renderer = $e->getRenderer();
    if ($this->renderer !== $renderer) {
        return;
    }
}

public function injectResponse(ViewEvent $e)
{
    $renderer = $e->getRenderer(); // Always null

    if ($this->renderer !== $renderer) {
        return;
    }
    $result = $e->getResult();
    $response = $e->getResponse();
    $response->setContent($result);
}

ViewYamlRenderer.php

public function render($nameOrModel, $values = null)
{
    return $nameOrModel->serialize();
}

public function setResolver(\Zend\View\Resolver\ResolverInterface $resolver)
{
    $this->resolver = $resolver;
}

YamlModel.php

protected $captureTo = null;
protected $terminate = true;

public function serialize()
{
    /*Serialize Object and return a string*/
}

感谢

2 个答案:

答案 0 :(得分:0)

认为这是由于触发策略/听众的顺序;一旦找到ViewRender,就会暂停事件传播并返回渲染器。

似乎标准PhpRenderStrategy默认事件优先级为1,其他(JsonStrategy等)似乎触发之前< / em>到此(优先级为100

尝试更改$priority;也许101

$this->listeners[] = $events->attach(
  ViewEvent::EVENT_RENDERER, 
  [$this, "selectRenderer"], 
  101 // <-- change here
); 

答案 1 :(得分:0)

我终于找到了问题。

<强> ViewYamlStrategy.php

/* This should return a renderer */
public function selectRenderer(ViewEvent $e)
{
    // here I was checking the Renderer which was not created yet
    // and instead I should've checked the model
    $model = $e->getModel();
    if (!$model instanceof YamlModel) {
        return;
    }
    return $this->renderer;
}