BaseBean.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Http\Bean;
  3. use Illuminate\Database\Eloquent\Model;
  4. class BaseBean
  5. {
  6. /**
  7. * 构造函数
  8. * @param $data 数据集
  9. */
  10. public function __construct($data = [])
  11. {
  12. if ($data instanceof Model) {
  13. $data = $data->toArray();
  14. }
  15. if (!empty($data)) {
  16. foreach ($data as $key => $val) {
  17. if (property_exists($this, $key) && !is_null($val)) {
  18. $setMethodName = $this->getSetMethodName($key);
  19. if (method_exists($this, $setMethodName)) {
  20. $this->$setMethodName($val);
  21. } else {
  22. $this->$key = $val;
  23. }
  24. }
  25. }
  26. }
  27. }
  28. /**
  29. * 获取set方法名称
  30. * @param $key
  31. * @return string
  32. */
  33. protected function getSetMethodName($key)
  34. {
  35. return "set" . ucfirst($key);
  36. }
  37. /**
  38. * 获取get方法名称
  39. * @param $key
  40. * @return string
  41. */
  42. protected function getGetMethodName($key)
  43. {
  44. return "get" . ucfirst($key);
  45. }
  46. public function toArray()
  47. {
  48. $data = [];
  49. //获取所有属性
  50. $reflectInstance = new \ReflectionClass(get_class($this));
  51. $properties = $reflectInstance->getProperties();
  52. foreach ($properties as $property){
  53. $key = $property->getName();
  54. $getMethodName = $this->getGetMethodName($key);
  55. $data[$key] = method_exists($this, $getMethodName) ? $this->$getMethodName() : $this->$key;
  56. if(is_null($data[$key])){
  57. unset($data[$key]);
  58. }
  59. }
  60. return $data;
  61. }
  62. }