3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\ModuleManager\Listener
;
12 use Zend\EventManager\EventManagerInterface
;
13 use Zend\EventManager\ListenerAggregateInterface
;
14 use Zend\Loader\ModuleAutoloader
;
15 use Zend\ModuleManager\ModuleEvent
;
18 * Module loader listener
20 class ModuleLoaderListener
extends AbstractListener
implements ListenerAggregateInterface
25 protected $moduleLoader;
30 protected $generateCache;
35 protected $callbacks = array();
40 * Creates an instance of the ModuleAutoloader and injects the module paths
43 * @param ListenerOptions $options
45 public function __construct(ListenerOptions
$options = null)
47 parent
::__construct($options);
49 $this->generateCache
= $this->options
->getModuleMapCacheEnabled();
50 $this->moduleLoader
= new ModuleAutoloader($this->options
->getModulePaths());
52 if ($this->hasCachedClassMap()) {
53 $this->generateCache
= false;
54 $this->moduleLoader
->setModuleClassMap($this->getCachedConfig());
61 public function attach(EventManagerInterface
$events)
63 $this->callbacks
[] = $events->attach(
64 ModuleEvent
::EVENT_LOAD_MODULES
,
65 array($this->moduleLoader
, 'register'),
69 if ($this->generateCache
) {
70 $this->callbacks
[] = $events->attach(
71 ModuleEvent
::EVENT_LOAD_MODULES_POST
,
72 array($this, 'onLoadModulesPost')
80 public function detach(EventManagerInterface
$events)
82 foreach ($this->callbacks
as $index => $callback) {
83 if ($events->detach($callback)) {
84 unset($this->callbacks
[$index]);
92 protected function hasCachedClassMap()
95 $this->options
->getModuleMapCacheEnabled()
96 && file_exists($this->options
->getModuleMapCacheFile())
107 protected function getCachedConfig()
109 return include $this->options
->getModuleMapCacheFile();
115 * Unregisters the ModuleLoader and generates the module class map cache.
117 * @param ModuleEvent $event
119 public function onLoadModulesPost(ModuleEvent
$event)
121 $this->moduleLoader
->unregister();
122 $this->writeArrayToFile(
123 $this->options
->getModuleMapCacheFile(),
124 $this->moduleLoader
->getModuleClassMap()