请参阅下面添加您自己的视图策略的示例,您可以在文档中查看示例:
http://framework.zend.com/manual/2.0/en/modules/zend.view.quick-start.html
如果这是您想要的方式,很容易修改示例以检查给定的控制器/操作。
<?php
namespace Application;
class Module
{
public function onBootstrap($e)
{
// Register a "render" event, at high priority (so it executes prior
// to the view attempting to render)
$app = $e->getApplication();
$app->getEventManager()->attach('render', array($this, 'registerJsonStrategy'), 100);
}
public function registerJsonStrategy($e)
{
$app = $e->getTarget();
$locator = $app->getServiceManager();
$view = $locator->get('Zend\View\View');
$phpStrateogy = $locator->get('PhpRendererStrategy');
// or any you have setup in your config...
$jsonStrategy = $locator->get('ViewJsonStrategy');
$routeMatch = $e->getRouteMatch();
/* @var $routeMatch \Zend\Mvc\Router\RouteMatch */
$routeName = $routeMatch->getMatchedRouteName();
if($routeName == 'myroute') {
// possible change layout?
//$controller->layout('app/layout/new_layout');
// Attach strategy, which is a listener aggregate, at high priority
//$view->getEventManager()->attach($jsonStrategy , 100);
$view->getEventManager()->attach($phpStrateogy, 1);
}
}
}
或者,您可以只返回不同类型的 ViewModel,如果启用了两种策略,您可以通过在控制器中返回不同的模型来更改使用的策略:
public function someAction()
{
// will use JsonRenderer
return new \Zend\View\Model\JsonModel(array('bob'));
// Will use PHPRenderer
return new \Zend\View\Model\ViewModel(array('bob'));
}