70907

Question:
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.
Answer1:this is called <a href="http://www.yiiframework.com/wiki/198/single-table-inheritance/" rel="nofollow">single table inheritance</a>.
Basically you overwrite the <a href="http://www.yiiframework.com/doc/api/1.1/CActiveRecord#instantiate-detail" rel="nofollow">instantiate</a> 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;
}