Skip to content

Instantly share code, notes, and snippets.

@raykolbe
Created March 19, 2013 12:44
Show Gist options
  • Save raykolbe/5195798 to your computer and use it in GitHub Desktop.
Save raykolbe/5195798 to your computer and use it in GitHub Desktop.
ZF2 navigation auto-inject to viewmodel
<?php
namespace Application;
use Zend\EventManager\EventInterface;
use Zend\ModuleManager\Feature\BootstrapListenerInterface;
class Module implements BootstrapListenerInterface,
{
/**
* {@inheritDoc}
*/
public function onBootstrap(EventInterface $event)
{
$application = $event->getParam('application');
$serviceManager = $application->getServiceManager();
$eventManager = $application->getEventManager();
$eventManager->attach('render', array($this, 'injectNavigationIntoViewModel'));
}
public function injectNavigationIntoViewModel($event)
{
$model = $event->getViewModel();
if (get_class($model) != 'Zend\View\Model\ViewModel') {
// We compare class instead of instance since some models might extend viewmodel.
return;
}
$app = $event->getApplication();
$sm = $app->getServiceManager();
$model->setVariable('navigation', $sm->get('Navigation'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment