Yii2路由在模块中的定义 [英] Yii2 routes definition in modules

查看:153
本文介绍了Yii2路由在模块中的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么解决方案可以通过模块配置添加路由吗?

Is there any solution to add routes from module configuration?

示例。我们在主要配置中描述了

Example. We have main config where we describe

'components' => [
    'urlManager' => [
                'enablePrettyUrl' => true,
                'showScriptName' => false,
                'rules' => require(FILE_PATH_CONFIG_ENV . '_routes.php') // return array
    ],
]

在每个模块中,我们使用私有参数加载自定义配置文件

in each module we load custom config file with private parameters

public function loadConfig($sFileName = 'main', $sFolderName = 'config')
{
    Yii::configure($this, require($this->getBasePath() . DS . $sFolderName . DS . $sFileName . '.php'));

    return $this;
}

配置文件

return [
    'components' => [
        'urlManager' => [
            'class' => 'yii\web\UrlManager',
            'rules' => [
                '/admin' => '/admin/index/index',
            ]
        ]
    ]
];

现在我需要以某种方式将当前配置(主要用于Web应用程序)与从模块加载的配置合并。最后,我只想在模块配置路由中对此模块进行描述,并将其用于漂亮的url(用户友好的url)。我该怎么办?当我创建网址 / admin / index / index 时,此示例不起作用,它显示了 / admin / index / index 但是我想要 / admin ,如模块规则中所述。

And now I need somehow merge current config (main for web application) with config loaded from module. In end I want describe in module config routes only for this module and use them for pretty urls (user friendly url). How can I do this one? This examples not working when I create url /admin/index/index, it shows me /admin/index/index but I want /admin as mentioned in module rules.

推荐答案

分离官方文档此处

我认为这是一种更理想的方法,与在一个配置文件中合并和声明所有规则不同。

And I think this is more optimum approach unlike merging and declaring all rules in one config file.

按照声明的顺序对规则进行解析(此处),因此,通过分隔,您可以跳过其他模块的网址。如果存在大量规则,则可以提高性能。

The rules are parsed in order they are declared (this is mentioned here), so with the separation you can skip other modules urls. In case of large amount of rules it can give perfomance boost.

这篇关于Yii2路由在模块中的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆