Yii2上具有别名的命名空间与目录结构不同 [英] Namespace with alias on Yii2 different from directory structure

查看:258
本文介绍了Yii2上具有别名的命名空间与目录结构不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了很多课程,并将它们放在目录 common/a/b/c 中. 因此,内部文件

I made a bunch of classes and put them inside the directory common/a/b/c. So, inside file

Class1.class.php

Class1.class.php

我有:

<?php
namespace x\y\b\c;
class Class1
...

命名空间不同于目录结构组织,因为我想要那样. ( x \ y 应该映射到 common/a 目录) 在我的 common/config/bootstrap.php 上,我尝试了以下操作:

Namespace is different from the directory structure organization, because I wanted that way. (x\y should map to common/a directory) On my common/config/bootstrap.php I tried this:

Yii::setAlias('common', dirname(__DIR__));
Yii::setAlias('x/y', '@common/a');

并尝试使用

use x\y\b\c\Class1;

没有成功.但是,如果我使用:

With no success. But if I use:

Yii::$classMap['x\y\b\c\Class1'] = __DIR__ . '/../../common/a/b/c/Class1.class.php';

代替 setAlias ,它起作用了.

我想知道是否有可能在不使用composer的情况下使名称空间不同于目录结构,以及如何在 common/a/b/c

I wonder if it's possible to have namespace different from the directory structure without using composer and how can I do this instead of mapping every class inside common/a/b/c

推荐答案

在bootstrap.php中.

In bootstrap.php.

Yii::setAlias('common', dirname(__DIR__));
Yii::setAlias('x/y', dirname(__DIR__).'/models');

在我的模型"文件夹中,有文件夹"b",文件夹"c"在文件夹"b"中.

Inside my "models" folder, there is folder "b" and folder "c" is inside folder "b".

models > b > c

我有一个名为"LoginForm.php"的模型文件,并且位于文件夹"c"中. 该文件的顶部是以下几行.

I have a model file named "LoginForm.php" and resides in folder "c". At the top of this file are these few lines.

namespace x\y\b\c;
use Yii;
use yii\base\Model;
class LoginForm extends Model

在我的SiteController中,我有这个.

Inside my SiteController I have this.

use x\y\b\c\LoginForm;

在其中一个动作函数中,我可以成功调用此模型.

In one of the action function, i can successfully call this model.

$model = new LoginForm();

这篇关于Yii2上具有别名的命名空间与目录结构不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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