http://my.oschina.net/phpyer/blog/189735
在Zf2中,一般的情况下,在modules的的某个模块的controller目录下添加一个controller 文件,对应的需要在module.config.php 中注册。 这样是为了启用灵活,但是当controller 文件特别多的时候,注册controller 的时候就感觉很繁琐,所有添加配置,实现Controller按照URL自动注册。
例如:Application 模块,在其controller目录下有两个controller 文件。如图:
IndexController已经在module.config.php 中注册,而UsersController没有注册。如图:
在UsersController文件中,写一个测试的action :
1 | public function testAutoAction(){ |
在浏览器中访问通过正确的URL 访问测试action 时,出现错误。如图:
从错误信息可以看出,UsersController 没有注册。如何解决它,那么就需要注册UsersController了。
一种方法是在module.config.php 中添加UsersController 的注册信息。
1 | 'controllers' => array( |
3 | 'Application\Controller\Index' => 'Application\Controller\IndexController', |
4 | 'Application\Controller\Users' => 'Application\Controller\UsersController' |
另一种方法是当你不想每添加一个controller时,去注册一次,那么就使用如下的方法。
1、创建一个抽象工厂
02 | namespace Application\Services; |
03 | use Zend\ServiceManager\AbstractFactoryInterface; |
04 | use Zend\ServiceManager\ServiceLocatorInterface; |
05 | class CommonControlAppAbstractFactory implements AbstractFactoryInterface{ |
08 | public function canCreateServiceWithName(ServiceLocatorInterface $locator, $name, $requestedName){ |
09 | if(class_exists($requestedName.'Controller')){ |
15 | public function createServiceWithName(ServiceLocatorInterface $locator, $name, $requestedName){ |
16 | $class = $requestedName.'Controller'; |
2、注册到getControllerConfig()
2 | public function getControllerConfig(){ |
4 | 'abstract_factories'=>array('Application\Services\CommonControlAppAbstractFactory') |
再次运行

这样就大功告成了。
References :
1.http://samsonasik.wordpress.com/2012/12/23/zend-framework-2-automatic-controller-invokables-via-abstract-factories/
2.https://packages.zendframework.com/docs/latest/manual/en/index.html