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
12 use Zend\EventManager\EventManagerInterface
;
13 use Zend\EventManager\ListenerAggregateInterface
;
15 class ModuleRouteListener
implements ListenerAggregateInterface
17 const MODULE_NAMESPACE
= '__NAMESPACE__';
18 const ORIGINAL_CONTROLLER
= '__CONTROLLER__';
21 * @var \Zend\Stdlib\CallbackHandler[]
23 protected $listeners = array();
26 * Attach to an event manager
28 * @param EventManagerInterface $events
29 * @param int $priority
31 public function attach(EventManagerInterface
$events, $priority = 1)
33 $this->listeners
[] = $events->attach(MvcEvent
::EVENT_ROUTE
, array($this, 'onRoute'), $priority);
37 * Detach all our listeners from the event manager
39 * @param EventManagerInterface $events
42 public function detach(EventManagerInterface
$events)
44 foreach ($this->listeners
as $index => $listener) {
45 if ($events->detach($listener)) {
46 unset($this->listeners
[$index]);
52 * Listen to the "route" event and determine if the module namespace should
53 * be prepended to the controller name.
55 * If the route match contains a parameter key matching the MODULE_NAMESPACE
56 * constant, that value will be prepended, with a namespace separator, to
57 * the matched controller parameter.
62 public function onRoute(MvcEvent
$e)
64 $matches = $e->getRouteMatch();
65 if (!$matches instanceof Router\RouteMatch
) {
66 // Can't do anything without a route match
70 $module = $matches->getParam(self
::MODULE_NAMESPACE
, false);
72 // No module namespace found; nothing to do
76 $controller = $matches->getParam('controller', false);
78 // no controller matched, nothing to do
82 // Ensure the module namespace has not already been applied
83 if (0 === strpos($controller, $module)) {
87 // Keep the originally matched controller name around
88 $matches->setParam(self
::ORIGINAL_CONTROLLER
, $controller);
90 // Prepend the controllername with the module, and replace it in the
92 $controller = $module . '\\' . str_replace(' ', '', ucwords(str_replace('-', ' ', $controller)));
93 $matches->setParam('controller', $controller);