In Zend Framework 2, I tried using the following route:
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '/:username[/:action]',
'defaults' => array(
'__NAMESPACE__' => 'Website\Controller',
'controller' => 'User',
'action' => 'index',
),
),
'may_terminate' => true,
),
However, when going to http://www.example.com/MyUsernameHere
, I get a 404
not found error:
The requested controller could not be mapped to an existing controller class.
Controller: User(resolves to invalid controller class or alias: User)
It's almost like the router completely ignores the 'Website\Controller'
namespace and looks for User
without the namespace in front it.
So, if I manually enter the namespace like so:
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '/:username[/:action]',
'defaults' => array(
'controller' => 'Website\Controller\User',
'action' => 'index',
),
),
'may_terminate' => true,
),
then the page loads as expected.
What gives? Can the '__NAMESPACE__'
parameter not be used for controllers? The ZF2 website clearly gives an example using '__NAMESPACE__'
, but I cannot get it work in practice. Is the example wrong and outdated?
For this to work as you expected you have to attach the ModuleRouteListener
to the MVC event manager. You can do this in your module onBootstrap
method:
public function onBootstrap(MvcEvent $event)
{
//...
$application = $event->getApplication();
$eventManager = $application->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
//...
}
After you did that your code will work as expected.
They actually should have mentioned this in the page with the example that you referred to in your question. You can check for more details on the module route listener here in the Zend\Mvc documentation. They write there:
This listener determines if the module namespace should be prepended to the controller name. This is the case if the route match contains a parameter key matching the
MODULE_NAMESPACE
constant.