Using standalone Zend\View

by Mateusz Tymek — on Zend Framework, PHP

Head's up! This post was written back in 2013 and is very likely to contain outdated information.

Zend\View is pretty advanced rendering engine, with multiple useful features. It is working nicely within ZF2's MVC stack, where it is automatically configured for you. But how to use it without full MVC?

This can be useful in some situations: when building Your Own Microframework™, when creating an application based on ZF2 components, or (in my case) when working on module that is supposed to render something outside MVC flow. All of this projects can benefit from nested templates, multiple rendering engines, or pluggable architecture of Zend\View.

So, how to do that?

Let's start with standalone PhpRenderer. Its purpose is to take PHTML template, feed it with your data, and output HTML. It won't render nested templates, but it makes a good start.
In order to configure PhpRenderer, it's enough to tell it where to look for your view scripts:

// configuration
$resolver = new TemplatePathStack(array(
    'script_paths' => array('path/to/application/views')
$phpRenderer = new PhpRenderer();

// example usage
$viewModel = new ViewModel(array('userName' => 'John Doe'));
echo $phpRenderer->render($viewModel);

Now you can combine PhpRenderer into Zend\View\View, to benefit from its pluggable architecture. It is event-driven, and will trigger RENDERER event to look for rendering engine.
Note that you will have to use little hack (setting has_parent option on ViewModel) in order to retrieve output. This will likely change in ZF3.

$view = new View();
    ->attach(ViewEvent::EVENT_RENDERER, function () use ($phpRenderer) {
        return $phpRenderer;

// example usage
$viewModel = new ViewModel(array('userName' => 'John Doe'));

// force Zend\View return rendered content instead of triggering response event
$viewModel->setOption('has_parent', true);
echo $view->render($viewModel);

This allows you to unleash full power of Zend\View!
For instance this is how you can use nested templates to render script with surrounding layout:

$viewModel = new ViewModel(array('userName' => 'John Doe'));

$layout = new ViewModel();

// same hack as in above example
$layout->setOption('has_parent', true);
echo $view->render($layout);

Working examples are available on Github: mtymek / zendview-standalone-example.

comments powered by Disqus