Ben
Ben

Reputation: 62444

Get Yii model class based on type

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?

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

Upvotes: 0

Views: 209

Answers (1)

Asgaroth
Asgaroth

Reputation: 4334

this is called single table inheritance.

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

Upvotes: 2

Related Questions