US-1234
US-1234

Reputation: 1529

Creating Dynamic attributes,properties in model class - YII Framework

I am trying to create dynamic attributes, properties and rules in model class from one table values as columns.

Consider i have one table named "XXX" which has column "Name" now i want to create model class with rules,properties and attributes using the Name values stored in DB.

I am new to YII Framework Can anybody give idea to this ?

Upvotes: 0

Views: 2169

Answers (1)

DarkMukke
DarkMukke

Reputation: 2489

This is something i mocked up quickly, I hope it points ou in the right direction

$sql="SELECT 'Name' FROM XXX";
$names =$connection->createCommand($sql)->query()->readAll();

$myDynamicObject = new DynamicModel($names);

class DynamicModel extends CModel
{
    protected $_members = array();


    public function __construct($nameFields)
    {
        foreach ($nameFields as $member) {
            $this->_members[$member] = null;
        }

        parent::__construct();
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        $allMembers = implode(', ', array_keys($this->_members));
        return array(
            array($allMembers, 'required'),
        );
    }

    public function __get($attribute)
    {

        if (in_array($attribute, array_keys($this->_members))) {
            return $this->_members[$attribute];
        } else {
            return parent::__get($attribute);
        }
    }

    public function __set($attribute, $value)
    {
        if (in_array($attribute, array_keys($this->_members))) {
            return $this->_members[$attribute] = $value;
        } else {
            return parent::__set($attribute, $value);
        }
    }

    public function getAttributes()
    {
        return $this->_members;
    }

    public function setAttributes($attributes)
    {
        $this->_members = $attributes;
    }

}

Upvotes: 1

Related Questions