Yii2 Custom / Shorter Namespace

旧巷老猫 提交于 2019-12-12 00:53:16

问题


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

@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:

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

I could just have:

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).

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?


回答1:


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

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

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

Add run bootstrap.php at init app.

Edit file web/index.php, add this line after require 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();

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

Hope it helpful.



来源:https://stackoverflow.com/questions/40033580/yii2-custom-shorter-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!