在模型类中创建动态属性和属性

时间:2014-07-02 10:48:10

标签: sql dynamic yii model

我使用了代码

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

}

我在控制器中打印此模型但是 不是什么都没来......服务器错误来了......

"更多 服务器尝试完成请求时遇到意外情况。 错误代码:500"

1 个答案:

答案 0 :(得分:0)

CModel是一个抽象类,您至少需要实现attributeNames()函数。 在你的情况下,我猜以下应该足够了:

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