Runtime Polymorphism in Yii

New member to the forum and Yii … Hi all…

Can we achieve Factory Design implementation in Yii MVC Framework?

Model Classes


abstract class Product{}

class Shop1_Product extends Product{}

class Shop2_Product extends Product{}

In Controller


$product = new Product($config); // $config defines whether it is shop1 or shop2

$product->method_in_shop1_product(); // if $config is set as shop1

or

$product->method_in_shop2_product(); // if $config is set as shop2

I want my Model Layer to behave like a Factory which returns an object based on $config - Any thoughts? Is this possible in Yii.

My decision to use Yii or plain PHP depends on its support for this kind of implementation? have tried reading docs, didnt find any? Please help !!

You can add a static method "create" to your Product class, where you should return Shop1_Product or Shop2_Product instance depending on the specified config.

You should also look at CActiveRecord.instantiate() method. It can serve the same purpose but when a record is being retrieved from a database.