Skip to content

Instantly share code, notes, and snippets.

@weierophinney
Created March 16, 2012 19:40
Show Gist options
  • Save weierophinney/2052134 to your computer and use it in GitHub Desktop.
Save weierophinney/2052134 to your computer and use it in GitHub Desktop.
A way to mark a view model as terminal, and thus skip the layout
<?php
/**
* A listener attached as such:
* $app->events()->attach('route', $listener, -100);
*/
public function onRouteComplete($e)
{
$routeMatch = $e->getRouteMatch();
if (!$routeMatch) {
return;
}
$action = $routeMatch->getParam('action', false);
if (!$action || !strstr($action, 'ajax')) {
return;
}
$app = $e->getTarget();
$locator = $app->getLocator();
$view = $locator->get('Zend\View\View');
$jsonStr = $locator->get('Custom\View\JsonStrategy');
$view->addRendererStrategy($jsonStr, 100);
$app->events()->attach('dispatch', function($e) {
// logic from other gist here
}, -90);
}
<?php
namespace Custom\View;
use Zend\EventManager\EventCollection as Events,
Zend\EventManager\ListenerAggregate,
Zend\Mvc\MvcEvent,
Zend\Mvc\Router\RouteMatch,
Zend\View\Model as ViewModel;
class TerminateAjaxModelListener implements ListenerAggregate
{
protected $listeners = array();
*/
public function attach(Events $events)
{
// -90, so that it's between when a view model is auto-created, and when we inject it in the layout.
$this->listeners[] = $events->attach('dispatch', array($this, 'terminateViewModel'), -90);
}
public function detach(Events $events)
{
foreach ($this->listeners as $index => $listener) {
if ($events->detach($listener)) {
unset($this->listeners[$index]);
}
}
}
public function terminateViewModel(MvcEvent $e)
{
$result = $e->getResult();
if (!$result instanceof ViewModel) {
return;
}
$model = $e->getViewModel();
$model->setTerminal(true);
}
}
/*
* Grab the application eventmanager instance:
* $app = $e->getTarget();
* Attach this to the 'dispatch' event:
* $listener = new TerminateViewModelListener();
* $app->events->attach('dispatch', $listener);
* Make sure you do this only when you _know_ that the request
* should result in a response that doesn't require a layout --
* likely you can do this at the same time you register your
* custom JsonStrategy.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment