本文介绍了根据类型获取 Yii 模型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Yii 中是否有对类型模型的内置支持?例如,如果我有一个名为 Flashlight、Lock 和 Folder 的类,它们都扩展了我的产品活动记录模型,并且我想通过 Yii 关系确保它是类型化类而不是泛型,我该怎么做?

Is there any built in support in Yii for typed models? For instance, If I have a class called Flashlight, Lock, and Folder that all extend my Product active Record model and I want to make sure it the typed class rather than the generic via Yii relations, how would I do that?

目前我正在覆盖 __call 并且我对此并不满意.我觉得这可能是一个普遍的需求.

Currently I am overwriting __call and I'm not really happy about it. I feel like this is probably a common need.

推荐答案

这叫做 单表继承.

基本上你覆盖模型的 instantiate 方法来返回您需要的课程:

Basically you overwrite the instantiate method of the model to return the class you need:

// protected/models/Product.php
protected function instantiate($attributes){
    switch($attributes['type']){
        case 'flashlight':
            $class='Flashlight';
        break;
        case 'lock':
            $class='Lock';
        break;
        case 'folder':
            $class='Folder';
        break;
        default:
            $class=get_class($this);
    }
    $model=new $class(null);
    return $model;
}

这篇关于根据类型获取 Yii 模型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 19:21