zf2 新模块控制器在使用工厂时解析为无效控制器 class 或别名

zf2 new module controller resolves to invalid controller class or alias when using factories

我的应用程序模块配置中有以下内容:

'controllers' => [
        'factories' => [
            Application\Controller\IndexController::class => Application\Controller\IndexControllerFactory::class
        ],
    ],

这很好用。现在我是我的 serve module 我有几乎相同的:

'controllers' => array(
                    /**
                    'invokables' => array(
                            'Serve\Controller\Index' => 'Serve\Controller\IndexController',
                    ),
                    */

                    'factories' => array(
                            Controller\IndexController::class => Serve\Controller\IndexControllerFactory::class
                    )

            ),

当我加载主页时,我通过 api 服务控制器访问。这样做时,我在主页上遇到了这个问题:

Serve\Controller\Index (resolves to invalid controller class or alias: Serve\Controller\Index)

就像我说的,我通过 api 访问服务控制器,所以当通过系统作为 api 请求时可能是一个设置问题。

有趣的是当我这样做时它起作用了:

'controllers'=>array(
    'invokables' => array(
                    'Serve\Controller\Index' => 'Serve\Controller\IndexController',
            )),

不确定这里有什么问题

更新:

这似乎有效:

'factories' => array(
                    'Serve\Controller\Index' => IndexControllerFactory::class
            )       

但是我喜欢使用 ::class 语法

当您映射到控制器时,问题出在您的路由配置中:Serve\Controller\Index 但您要么从未使用 module.config 中的特定键注册该控制器,要么您使用了错误的值路由中的键“controller”,因为您在控制器映射中指定了 FQCN。

// module.config
'aliases' => [
    'Serve\Controller\Index' => Serve\Controller\IndexController:class,
],
'factories' => [
    Serve\Controller\IndexController:class => Serve\Controller\IndexControllerFactory::class,
],

或者在你的路由配置中不要使用 Serve\Controller\Index 但使用 FQCN,这样它就可以直接使用 Factory 而不是你设置的别名。喜欢:

// route.config
'serve' => [
    'type' => 'literal',
    'options' => [
        'route' => '/serve',
        'defaults' => [
            'controller' => Serve\Controller\IndexController::class,
            'action'     => 'index',
       ],
    ],
],

我一直在工厂映射中使用 FQCN 映射我的 类,如果我想用另一个名字调用它们,我会添加别名。因此,您现在可以使用 FQCN 或其任何别名,例如:Serve\Controller\Index