2013-10-28 129 views
2

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

例如,我有:

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

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

如何做到这一点?

回答

4

不幸的Yii不提供任何本地方法来确定模型属于模块名称。你必须编写自己的算法来完成这项任务。

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

  1. 在模块类模块的型号存储配置。

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

    在配置

  2. 使用路径别名

第一种方法提供模型的名称:

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

分公司。PHP:

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

    // Other code 
} 
2

试试这个:

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

或控制器内:

$this->module->id 
+0

这仅仅获得当前模式的模块。但我想获得其他模块名称。 – Thyu

+0

正如Thyu所说,这会在控制台应用程序上抛出一个错误(甚至没有控制器)。 – mmitchell