Category.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace app\common\modules\category;
  3. class Category
  4. {
  5. private $attributes;
  6. private $children;
  7. private $categoryGroup;
  8. private $tree;
  9. public function __construct($attributes, CategoryGroup $categoryGroup)
  10. {
  11. unset($attributes['parent_id']);
  12. $this->attributes = $attributes;
  13. $this->categoryGroup = $categoryGroup;
  14. }
  15. private function getChildren()
  16. {
  17. if (!isset($this->children)) {
  18. $childrenAttributes = $this->categoryGroup->find($this->attributes['id']);
  19. $this->children = [];
  20. foreach ($childrenAttributes as $attributes) {
  21. $this->children[] = new static($attributes, $this->categoryGroup);
  22. }
  23. }
  24. return $this->children;
  25. }
  26. public function getChildrenTree($level = 99)
  27. {
  28. return $this->tree($level)['childrens'] ?: [];
  29. }
  30. public function tree($level)
  31. {
  32. // 缓存指定层级数据
  33. if (!isset($this->tree[$level])) {
  34. $this->tree[$level] = $this->attributes;
  35. $this->tree[$level]['childrens'] = [];
  36. if ($level == 0) {
  37. $this->tree[$level]['childrens'] = [];
  38. } else {
  39. // 按层级递减,返回$level层
  40. foreach ($this->getChildren() as $category) {
  41. $this->tree[$level]['childrens'][] = $category->tree($level - 1);
  42. }
  43. }
  44. }
  45. return $this->tree[$level];
  46. }
  47. }