Yii2自定义/较短的命名空间 [英] Yii2 Custom / Shorter Namespace

查看:273
本文介绍了Yii2自定义/较短的命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的yii2(基本模板)中的以下位置有一个嵌套的邮件"模块:

I have a nested 'mail' module in my yii2 (basic template) at this location:

@ app/modules/admin/modules/mail

@app/modules/admin/modules/mail

如何在所有模块文件中创建较短的名称空间.因此,而不是在我的控制器文件中使用此名称空间:

How do I create shorter namespaces in all of the modules files. So instead of this namespace in my controller files:

命名空间app \ modules \ admin \ modules \ mail \ controllers;

namespace app\modules\admin\modules\mail\controllers;

我可以拥有:

命名空间邮件/控制器;

namespace mail/controllers;

如果我移动了模块文件夹,则不必去手动更改每个文件中的名称空间(它们也很长).

If I ever move the module folder, I wouldn't have to go and manually change the namespace in every single file (also they're just long).

文档实际上在这里推荐此操作 http://www.yiiframework.com/doc-2.0/guide-structure-modules.html#nested-modules 上显示"您应该考虑在此处使用较短的名称空间!"

The docs actually recommend this here http://www.yiiframework.com/doc-2.0/guide-structure-modules.html#nested-modules where it says "you should consider using a shorter namespace here!"

但是您如何做到这一点?

But how do you accomplish this?

推荐答案

您必须在引导程序中为自定义名称空间的目录设置别名.

you must set alias to directory at bootstrap to custom namespace.

首先,在config/文件夹中创建一个bootstrap.php:

First, create a bootstrap.php in config/ folder:

//bootstrap.php
Yii::setAlias('mail', dirname(dirname(__DIR__)) . '/modules/admin/modules/mail');

在初始化应用中添加运行bootstrap.php.

Add run bootstrap.php at init app.

编辑文件web/index.php,在需要Yii.php

require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');

//Add after require Yii.php
require(__DIR__ . '/../config/bootstrap.php');

$config = require(__DIR__ . '/../config/web.php');
(new yii\web\Application($config))->run();

现在您可以在邮件模块中为控制器设置命名空间为mail/controllers.

Now you can set namespace for controllers in mail module is mail/controllers.

希望对您有所帮助.

这篇关于Yii2自定义/较短的命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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