Skip to content

Instantly share code, notes, and snippets.

@skl
Created September 16, 2015 16:13
Show Gist options
  • Save skl/cbf4580fcbf546eb6fa2 to your computer and use it in GitHub Desktop.
Save skl/cbf4580fcbf546eb6fa2 to your computer and use it in GitHub Desktop.
ZF2 ModuleEvent listener that prioritises `ViewJsonStrategy` over `ZfcTwigViewStrategy` in order to properly render a JsonModel.
<?php
namespace Application;
use Zend\ModuleManager\ModuleEvent;
use Zend\ModuleManager\ModuleManager;
/**
* Class Module
* @package Application
*/
class Module
{
/**
* @param ModuleManager $moduleManager
*/
public function init(ModuleManager $moduleManager)
{
$events = $moduleManager->getEventManager();
$events->attach(ModuleEvent::EVENT_MERGE_CONFIG, [$this, 'onMergeConfig']);
}
/**
* @param ModuleEvent $e
*/
public function onMergeConfig(ModuleEvent $e)
{
$configListener = $e->getConfigListener();
$config = $configListener->getMergedConfig(false);
// If both ZfcTwigViewStrategy and ViewJsonStrategy registered, prioritise ViewJsonStrategy, this fixes an issue
// with the zfctwig module where it was trying to load layouts for JsonModel responses.
if (isset($config['view_manager']['strategies'])
&& false !== array_search('ViewJsonStrategy', $config['view_manager']['strategies'])
&& false !== ($zfcKey = array_search('ZfcTwigViewStrategy', $config['view_manager']['strategies']))
) {
unset($config['view_manager']['strategies'][$zfcKey]);
array_push($config['view_manager']['strategies'], 'ZfcTwigViewStrategy');
$configListener->setMergedConfig($config);
}
}
@skl
Copy link
Author

skl commented Sep 16, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment