Thyu
Thyu

Reputation: 109

Getting module's name from model's name

I need to know a module name for a particular model, if I know only model's name.

For example, I have:

I want to know the module name of branch.php from the class of branchtype.php.

How to do this?

Upvotes: 4

Views: 7670

Answers (3)

Malki Mohamed
Malki Mohamed

Reputation: 1688

in Yii2 try this:

echo Yii::$app->controller->module->id;

for more information see Get the current controller name, action, module

Upvotes: 0

Pavel Agalecky
Pavel Agalecky

Reputation: 120

Unfortunately Yii does not provide any native method to determine the module name that model belongs to. You have to write your own algorithm to do this task.

I can suppose you two possible methods:

  1. Store configuration for module's models in the module class.
  2. Provide the name of your model using path aliases

First method:

MyModule.php:

class MyModule extends CWebModule
{
    public $branchType = 'someType';
}

Branch.php

class Branch extends CActiveRecord
{
    public function init() // Or somewhere else
    {
        $this->type = Yii::app()->getModule('my')->branchType;
    }
}

In configuration:

'modules' =>
    'my' => array(
        'branchType' => 'otherType',
    )

Second method:

In configuration:

'components' => array(
    'modelConfigurator' => array(
        'models' => array(
            'my.models.Branch' => array(
                'type' => 'someBranch'
            ),
        ),
    ),
)

You should write component ModelConfigurator that will store this configuration or maybe parse it in some way. Then you can do something like this:

BaseModel.php:

class BaseModel extends CActiveRecord
{
    public $modelAlias;

    public function init()
    {
        Yii::app()->modelConfigurator->configure($this, $this->modelAlias);
    }
}

Branch.php:

class Branch extends BaseModel
{
    public $modelAlias = 'my.models.Branch';

    // Other code
}

Upvotes: 5

naveen goyal
naveen goyal

Reputation: 4629

Try this:

Yii::app()->controller->module->id.

Or inside a controller:

$this->module->id

Upvotes: 3

Related Questions