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

时间:2013-10-28 08:13:51

标签: php yii model module

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

例如,我有:

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

我想知道branch.phpbranchtype.php的模块名称。

怎么做?

3 个答案:

答案 0 :(得分:4)

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

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

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

    第一种方法:

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

    在配置中:

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

    第二种方法:

    在配置中:

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

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

    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
    }
    

答案 1 :(得分:2)

试试这个:

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

或在控制器内:

$this->module->id

答案 2 :(得分:0)

在Yii2中

试试这个:

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

有关详细信息,请参阅Get the current controller name, action, module