Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • model Branch, stored in protected/modules/office/models/branch.php and
  • model BranchType stored in protected/modules/config/models/branchtype.php.

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

How to do this?

like image 676
Thyu Avatar asked Feb 14 '23 20:02

Thyu


1 Answers

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
}
like image 158
Pavel Agalecky Avatar answered Feb 17 '23 11:02

Pavel Agalecky