Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. public function getTrail()
  2. {
  3.  
  4. $parent = $this -> parent();
  5.  
  6. $trail = array();
  7.  
  8. while($parent !== NULL)
  9. {
  10.  
  11. // push parent element to trail
  12. $trail[] = $parent;
  13.  
  14. // go backwards one node
  15. $parent = $parent -> parent();
  16.  
  17. }
  18.  
  19. // you want trail in reverse order [from root to latest]
  20. return array_reverse($trail);
  21.  
  22. }
  23.  
  24. class TreeNode {
  25. /**
  26. * the parent node
  27. *
  28. * @var TreeNode
  29. */
  30. private $parentNode=null;
  31. /**
  32. * the children of this node
  33. *
  34. * @var TreeNode[]
  35. */
  36. private $children=array();
  37. /**
  38. * The user element this tree node holds.
  39. *
  40. * @var Object
  41. */
  42. private $element;
  43. }
  44.  
  45. interface BreadcrumbInterface
  46. {
  47. public function getLabel();
  48.  
  49. public function getParent(); // returns an instance of BreadcrumbInterface, or null
  50. }
  51.  
  52. abstract class BaseNode implements BreadcrumbInterface
  53. {
  54. protected $parent = null;
  55.  
  56. public function accept(BreadcrumbVisitor $visitor)
  57. {
  58. $visitor->visit($this);
  59. }
  60.  
  61. public function setParent(BreadcrumbInterface $parent)
  62. {
  63. $this->parent = $parent;
  64. }
  65.  
  66. public function getParent()
  67. {
  68. return $this->parent;
  69. }
  70. }
  71.  
  72. class BreadcrumbVisitor
  73. {
  74. protected $breadcrumbs = array();
  75.  
  76. public function visit(BreadcrumbInterface $node)
  77. {
  78. $parent = $node->getParent();
  79. if ($parent instanceof BaseNode) {
  80. $parent->accept($this);
  81. }
  82.  
  83. $this->breadcrumbs[] = $node->getLabel();
  84. }
  85.  
  86. public function getBreadcrumbs()
  87. {
  88. return $this->breadcrumbs;
  89. }
  90. }
  91.  
  92. $rootPage = new Page(/*...*/);
  93.  
  94. $parentPage = new Page(/*...*/);
  95. $parentPage->setParent($rootPage); // In reality you most likely wouldn't be building this structure so explicitly. Each object only needs to know about it's direct parent
  96.  
  97. $currentPage = new Page(/*...*/);
  98. $currentPage->setParent($parentPage);
  99.  
  100. $visitor = new BreadcrumbVisitor();
  101. $currentPage->accept($visitor);
  102. $breadcrumbs = $visitor->getBreadcrumbs(); // returns an array, where the first element is the root
  103.  
  104. // then you can implode with ' > ' if you want
  105. $breadcumbString = implode(' > ', $breadcrumbs);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement