CommonEntity.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace app\entity;
  3. use app\utils\ArrayUtil;
  4. use ReflectionClass;
  5. class CommonEntity
  6. {
  7. /**
  8. * 将 参数 实例化到 实体
  9. * @param array $data
  10. * @return static|self
  11. */
  12. public static function newInstance(array $data = []): self
  13. {
  14. if (empty($data)) {
  15. return new static();
  16. } else {
  17. $instance = new static();
  18. $data = ArrayUtil::underline2CamelArr($data);
  19. foreach ($instance as $ik => $iv) {
  20. if (isset($data[$ik])) {
  21. $setFunctionName = 'set' . ucfirst($ik);
  22. $instance->$setFunctionName($data[$ik]);
  23. }
  24. }
  25. return $instance;
  26. }
  27. }
  28. /**
  29. * 声明公共方法 将实体 转成数组
  30. * @return array
  31. */
  32. public function toArray(): array
  33. {
  34. $data = [];
  35. try {
  36. $ref = new ReflectionClass(static::class);
  37. foreach ($ref->getProperties() as $property) {
  38. $p = $ref->getProperty($property->name);
  39. $p->setAccessible(true);
  40. $data[$property->name] = $p->getValue($this);
  41. }
  42. } catch (\Exception $e) {
  43. }
  44. return $data;
  45. }
  46. /**
  47. * 将实体属性(驼峰命名)转换为下划线命名的数组
  48. * 用于数据库写入
  49. * @return array
  50. */
  51. public function toUnderlineArray(): array
  52. {
  53. $result = [];
  54. $camelArray = $this->toArray(); // 先获取驼峰格式的数组
  55. foreach ($camelArray as $key => $value) {
  56. if (is_null($value)) {
  57. continue;
  58. }
  59. // 将驼峰键名转为下划线格式
  60. $underlineKey = $this->camelToUnderline($key);
  61. $result[$underlineKey] = $value;
  62. }
  63. return $result;
  64. }
  65. /**
  66. * 驼峰命名转下划线命名
  67. * @param string $camel
  68. * @return string
  69. */
  70. private function camelToUnderline(string $camel): string
  71. {
  72. // 处理连续大写字母(如 "userID" 转 "user_id")
  73. $camel = preg_replace('/([A-Z]+)([A-Z][a-z])/', '$1_$2', $camel);
  74. // 将大写字母前添加下划线并转为小写
  75. return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $camel));
  76. }
  77. }