如果我只知道模型的名称,我需要知道特定模型的模块名称。
例如,我有:
Branch
,存储在protected/modules/office/models/branch.php
和BranchType
存储在protected/modules/config/models/branchtype.php
。我想知道branch.php
类branchtype.php
的模块名称。
怎么做?
答案 0 :(得分:4)
不幸的是,Yii没有提供任何本机方法来确定模型所属的模块名称。您必须编写自己的算法来执行此任务。
我可以假设你有两种可能的方法:
第一种方法:
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)
试试这个:
echo Yii::$app->controller->module->id;