Collection.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace addons\posters\lib;
  3. abstract class Collection
  4. {
  5. /**
  6. * The collection data.
  7. *
  8. * @var array
  9. */
  10. protected $items = [];
  11. /**
  12. * 只读属性 外部不能修改
  13. *
  14. * @var array
  15. */
  16. protected $readonly = [];
  17. /**
  18. * set data.
  19. *
  20. * @param mixed $items
  21. */
  22. public function __construct(array $items = [])
  23. {
  24. foreach ($items as $key => $value) {
  25. $this->set($key, $value);
  26. }
  27. }
  28. /**
  29. * Get a data by key.
  30. *
  31. * @return mixed
  32. */
  33. public function __get(string $key)
  34. {
  35. return $this->get($key);
  36. }
  37. public function __set(string $key, $value)
  38. {
  39. return $this->set($key, $value);
  40. }
  41. public function __call(string $key, $value)
  42. {
  43. return count($value) > 0 ? $this->set($key, $value[0]) : $this->get($key);
  44. }
  45. public function __isset(string $key): bool
  46. {
  47. return $this->has($key);
  48. }
  49. public function all(): array
  50. {
  51. return $this->items;
  52. }
  53. public function has(string $key): bool
  54. {
  55. return !is_null($this->get($key));
  56. }
  57. public function get(string $key, $default = null)
  58. {
  59. return $this->items[$key] ?? $default;
  60. }
  61. public function set(string $key, $value)
  62. {
  63. if (isset($this->items[$key]) && !in_array($key, $this->readonly)) {
  64. $method = "set".ucfirst(strtolower($key))."Attr";
  65. if (method_exists($this, $method)){
  66. $this->$method($value);
  67. }else{
  68. $this->items[$key] = $value;
  69. }
  70. }
  71. return $this;
  72. }
  73. }