StackUnder
StackUnder

Reputation: 252

Namespace with alias on Yii2 different from directory structure

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

Upvotes: 1

Views: 1952

Answers (1)

Hanafi
Hanafi

Reputation: 151

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

Upvotes: 1

Related Questions