Last active
August 29, 2015 14:05
-
-
Save gkralik/7521ac90a49b3473ca1a to your computer and use it in GitHub Desktop.
ZF2 listener to set ViewModel's terminal property if request is XHR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Attach XhrTerminalViewModelListener in module's onBootstrap() method. | |
* | |
* <code> | |
* public function onBootstrap(MvcEvent $e) | |
* { | |
* $app = $e->getApplication(); | |
* $eventManager = $app->getEventManager(); | |
* $eventManager->attach(new XhrTerminalViewModelListener()); | |
* | |
* /* [...] */ | |
* } | |
* </code> | |
*/ | |
namespace Application\Listener; | |
use Zend\EventManager\EventManagerInterface; | |
use Zend\EventManager\ListenerAggregateInterface; | |
use Zend\Mvc\MvcEvent; | |
use Zend\View\Model\ViewModel; | |
class XhrTerminalViewModelListener implements ListenerAggregateInterface | |
{ | |
protected $listeners = array(); | |
/** | |
* @inheritdoc | |
*/ | |
public function attach(EventManagerInterface $events) | |
{ | |
$sharedEvents = $events->getSharedManager(); | |
/** @noinspection PhpVoidFunctionResultUsedInspection */ | |
$this->listeners[] = $sharedEvents->attach( | |
'Zend\Mvc\Controller\AbstractController', | |
'dispatch', | |
array($this, 'setXhrTerminal'), | |
-99 | |
); | |
} | |
/** | |
* @inheritdoc | |
*/ | |
public function detach(EventManagerInterface $events) | |
{ | |
foreach ($this->listeners as $index => $listener) { | |
if ($events->detach($listener)) { | |
unset($this->listeners[$index]); | |
} | |
} | |
} | |
/** | |
* Set ViewModel 'terminate' property to true if request is XHR. | |
* @param MvcEvent $e | |
*/ | |
public function setXhrTerminal($e) | |
{ | |
$result = $e->getResult(); | |
$request = $e->getApplication()->getRequest(); | |
if ($result instanceof ViewModel) { | |
$result->setTerminal($request->isXmlHttpRequest()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment