I've created 40 to 50 projects based on Zend Framework 2. As you can imagine, while working on those projects I've created lots of modules myself.
One or two times a ran into a strange problem, which only occured under certain circumstances. I digged deep into the code of Zend Framework to find the solution and I wanna share it in this post and hope it helps you, if you ever run into this problem, too.
I've created a module with a camel-cased-name, like ModuleCamelCased
. I created all the folders and filled the config with a routing- and a controller-definition. Everything as usual. The controller had an index
-action.
When I requested the route in my browser I got the exception, that the view-file couldn't be found for this action. But it was there. In the exception I noticed the resolver didn't look for module-camel-cased/index/index.phtml
but instead for module-camel-cased/controller/index/index.phtml
. I've never experienced it before - why did the resolver put the controller
into the path, where it looks for the view-file?
Up to this point I had the following configuration set in my config/module.config.php
:
<?php
// module.config.php
return [
'controllers' => [
'aliases' => [
'ModuleCamelCased\Controller\Index' => \ModuleCamelCased\Controller\IndexController::class
],
'invokables' => [
\ModuleCamelCased\Controller\IndexController::class => \ModuleCamelCased\Controller\IndexController::class
]
],
'router' => [
'routes' => [
'test' => [
'type' => 'Literal',
'options' => [
'route' => '/test',
'defaults' => [
'__NAMESPACE__' => '\ModuleCamelCased\Controller',
'controller' => 'index',
'action' => 'index'
]
]
]
]
],
'view_manager' => [
'template_path_stack' => [
__DIR__ . '/../view'
]
]
];
This as I said resulted in the exception, that ZF couldn't find the template module-camel-cased/controller/index/index.phtml
.
What I wanted was the resolver to search for module-camel-cased/index/index.phtml
instead of module-camel-case/controller/index/index.phtml
. The solution was rather simple in the end. In the routing-configuration just remove the first backslash in the __NAMESPACE__
of the defaults
:
'router' => [
'routes' => [
'test' => [
'type' => 'Literal',
'options' => [
'route' => '/test',
'defaults' => [
'__NAMESPACE__' => 'ModuleCamelCased\Controller',
'controller' => 'index',
'action' => 'index'
]
]
]
]
],
When specifying a __NAMESPACE__
-key within the defaults
of a route-config, dismiss the first backslash of the namespace.
I hope this helps you!