DynamicModel.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. /**
  3. * 这是一个自定义的类,用于将数组转为 cmodel 对象
  4. * 配合 Helper::arrayToModel() 方法使用
  5. */
  6. class DynamicModel extends \CModel
  7. {
  8. private $_attributes = array();
  9. public function rules()
  10. {
  11. // 动态属性可以直接标记为安全
  12. return array(
  13. array(implode(',', array_keys($this->_attributes)), 'safe'),
  14. );
  15. }
  16. public function attributeNames()
  17. {
  18. // 返回属性名称
  19. return array_keys($this->_attributes);
  20. }
  21. public function __get($name)
  22. {
  23. // 获取属性值
  24. if (array_key_exists($name, $this->_attributes)) {
  25. return $this->_attributes[$name];
  26. } else {
  27. return parent::__get($name);
  28. }
  29. }
  30. public function __set($name, $value)
  31. {
  32. // 设置属性值
  33. $this->_attributes[$name] = $value;
  34. }
  35. public function setAttributes($values, $safeOnly = true)
  36. {
  37. // 批量设置属性值
  38. if (!is_array($values)) {
  39. return;
  40. }
  41. foreach ($values as $name => $value) {
  42. $this->$name = $value;
  43. }
  44. }
  45. }