Zend framework 3 路由器在单独的文件中(不在配置数组树中)

Zend framework 3 routers in separate file (not in config array tree)

我正在使用本教程 https://docs.zendframework.com/tutorials/getting-started/overview/ 创建相册模块。这个对我有用。

在项目中有 /module/Album/config/module.config.php 包含路由的文件。路由器位于数组树中。正如我以前的经验所示,未来我可以为每个项目(甚至每个模块)提供数十条路线。

在此文档页面上 https://docs.zendframework.com/zend-router/routing/ 我找到了另一种将路由器添加到模块的方法。

// One at a time:
$route = Literal::factory([
    'route' => '/foo',
    'defaults' => [
        'controller' => 'foo-index',
        'action'     => 'index',
    ],
]);
$router->addRoute('foo', $route);

我更喜欢这种方式,而不是将路由存储在非常深的配置数组树中。

所以,我的问题是:如前所述,我可以将 php 路由器代码放在配置树之外的什么地方?这样的路由器文件应该位于模块中的什么位置?

在模块 config/ 文件夹中的 module.config.php 旁边,通常会创建一个 routes.config.php

我通过 user.routes.config.phproles.routes.config.php 之类的操作进一步拆分它。可能您想要 front.routes.config.phpadmin.routes.config.php

最后,由您决定。为了同事和未来的理智,请确保您始终如一地这样做。


举个例子,我的一个项目中User模块的配置:

这是一个直接处理任何与用户相关的模块,所以它都在里面。可能应该将其拆分得更多,但就目前而言,这是不必要的。

然后您将像这样在 Module.php:

中加载所有这些配置
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;

class Module implements ConfigProviderInterface, AutoloaderProviderInterface
{

    /**
     * @return array
     */
    public function getConfig()
    {
        $config = [];

        $path = __DIR__
            . DIRECTORY_SEPARATOR . '..'
            . DIRECTORY_SEPARATOR . 'config'
            . DIRECTORY_SEPARATOR . '*.php';

        foreach (glob($path) as $filename) {
            $config = array_merge_recursive($config, include $filename);
        }

        return $config;
    }

    /**
     * @return array
     */
    public function getAutoloaderConfig()
    {
        return [
            'Zend\Loader\StandardAutoloader' => [
                'namespaces' => [
                    __NAMESPACE__ => __DIR__ . DIRECTORY_SEPARATOR . 'src',
                ],
            ],
        ];
    }
}

请记住,项目的最终实施取决于您。但是,制定一个标准并坚持下去。如果你到处都有不同的标准,你会发疯的。