Created
September 16, 2015 16:13
-
-
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.
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 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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Code originally taken from an example in the Zend documentation:
http://framework.zend.com/manual/current/en/tutorials/config.advanced.html#manipulating-merged-configuration