Namespace with alias on Yii2 different from directory structure

孤街浪徒 提交于 2019-12-13 02:36:09

问题


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

Class1.class.php

I have:

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

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');

And tried importing this class in another file using

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';

instead of setAlias, it works.

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


回答1:


In bootstrap.php.

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

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

models > b > 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

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();


来源:https://stackoverflow.com/questions/34723615/namespace-with-alias-on-yii2-different-from-directory-structure

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