从模型名称中获取模块名称

Thy*_*hyu 4 php model module yii

如果我只知道模型的名称,我需要知道特定模型的模块名称。

例如,我有:

  • 模型Branch,存储在protected/modules/office/models/branch.php
  • 模型BranchType存储在protected/modules/config/models/branchtype.php.

我想知道的模块名称branch.php从类的branchtype.php

这该怎么做?

Pav*_*cky 5

不幸的是 Yii 没有提供任何本地方法来确定模型所属的模块名称。您必须编写自己的算法来完成此任务。

我可以假设你有两种可能的方法:

  1. 在模块类中存储模块模型的配置。
  2. 使用路径别名提供模型的名称

第一种方法:

我的模块.php:

class MyModule extends CWebModule
{
    public $branchType = 'someType';
}
Run Code Online (Sandbox Code Playgroud)

分支.php

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

在配置中:

'modules' =>
    'my' => array(
        'branchType' => 'otherType',
    )
Run Code Online (Sandbox Code Playgroud)

第二种方法:

在配置中:

'components' => array(
    'modelConfigurator' => array(
        'models' => array(
            'my.models.Branch' => array(
                'type' => 'someBranch'
            ),
        ),
    ),
)
Run Code Online (Sandbox Code Playgroud)

您应该编写组件 ModelConfigurator 来存储此配置或以某种方式解析它。然后你可以做这样的事情:

基础模型.php:

class BaseModel extends CActiveRecord
{
    public $modelAlias;

    public function init()
    {
        Yii::app()->modelConfigurator->configure($this, $this->modelAlias);
    }
}
Run Code Online (Sandbox Code Playgroud)

分支.php:

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

    // Other code
}
Run Code Online (Sandbox Code Playgroud)