Created
March 15, 2012 19:57
-
-
Save weierophinney/2046461 to your computer and use it in GitHub Desktop.
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 | |
namespace Custom\View\Strategy; | |
use Zend\EventManager\EventCollection, | |
Zend\EventManager\ListenerAggregate, | |
Zend\Http\Request as HttpRequest, | |
Zend\Http\Response as HttpResponse, | |
Zend\View\Model, | |
Zend\View\Renderer\JsonRenderer, | |
Zend\View\ViewEvent; | |
class JsonStrategy implements ListenerAggregate | |
{ | |
protected $listeners = array(); | |
protected $renderer; | |
public function __construct(JsonRenderer $renderer) | |
{ | |
$this->renderer = $renderer; | |
} | |
public function attach(EventCollection $events, $priority = 1) | |
{ | |
$this->listeners[] = $events->attach('renderer', array($this, 'selectRenderer'), $priority); | |
$this->listeners[] = $events->attach('response', array($this, 'injectResponse'), $priority); | |
} | |
public function detach(EventCollection $events) | |
{ | |
foreach ($this->listeners as $index => $listener) { | |
if ($events->detach($listener)) { | |
unset($this->listeners[$index]); | |
} | |
} | |
} | |
public function selectRenderer(ViewEvent $e) | |
{ | |
// We assume if attached, this is the selected renderer. | |
// So, let's manipulate the view model' | |
$model = $e->getViewModel(); | |
$data = $model->getVariables(); | |
$request = $e->getRequest(); | |
// Create a new payload and use this as the view model | |
$payload = array( | |
'error' => /* logic for returning this */, | |
'isRedirect' => $request->isRedirect(), | |
'data' => $data, | |
); | |
$model = new JsonModel($payload); | |
$e->setViewModel($model); | |
// Now we can return the renderer | |
return $this->renderer; | |
} | |
public function injectResponse(ViewEvent $e) | |
{ | |
$renderer = $e->getRenderer(); | |
if ($renderer !== $this->renderer) { | |
// Discovered renderer is not ours; do nothing | |
return; | |
} | |
$result = $e->getResult(); | |
if (!is_string($result)) { | |
// We don't have a string, and thus, no JSON | |
return; | |
} | |
// Populate response | |
$response = $e->getResponse(); | |
$response->setContent($result); | |
$headers = $response->headers(); | |
$headers->addHeaderLine('content-type', 'application/json'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment