| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- <?php
- /**
- * 这是一个自定义的类,用于将数组转为 cmodel 对象
- * 配合 Helper::arrayToModel() 方法使用
- */
- class DynamicModel extends \CModel
- {
- private $_attributes = array();
- public function rules()
- {
- // 动态属性可以直接标记为安全
- return array(
- array(implode(',', array_keys($this->_attributes)), 'safe'),
- );
- }
- public function attributeNames()
- {
- // 返回属性名称
- return array_keys($this->_attributes);
- }
- public function __get($name)
- {
- // 获取属性值
- if (array_key_exists($name, $this->_attributes)) {
- return $this->_attributes[$name];
- } else {
- return parent::__get($name);
- }
- }
- public function __set($name, $value)
- {
- // 设置属性值
- $this->_attributes[$name] = $value;
- }
- public function setAttributes($values, $safeOnly = true)
- {
- // 批量设置属性值
- if (!is_array($values)) {
- return;
- }
- foreach ($values as $name => $value) {
- $this->$name = $value;
- }
- }
- }
|