0

I have a Site object but I can't figure out how best to store a collection of Page objects on Site. The pages are hierarchical (a tree structure for a website navigation). I thought about a tree-like array of pages but that would be a pain to interact with - e.g. $site->pages[0][3][1]->addContent('<h1>lol</h1>'). I could use a flat array of pages with unique IDs like $site->pages['home']->addContent('<p>easier</p>') but how would I extract a tree from that when it came to rendering navigation?

3 Answers 3

1

I would use URLs such as:

http://www.example.org/products/electronics/computer/monitors

And use code like this to represent the page:

$site->pages['products']['electronics']['computer']['monitors']

You can configure your web server to redirect all requests to your .php file, and you can "break" down the URL by exploding the REQUEST_URI variable.

Sign up to request clarification or add additional context in comments.

Comments

1

A good way is to use the composite pattern as Gordon says. A simple implementation of this could be :

interface SitePart {
  function getName();
}

class Page implements SitePart {
  function Page($name,$content) { ... }
  function getName() { ... }
  function getContent() { ... }
}

class Category implements SitePart {
  private $parts = array()
  function Category($name) { ... }
  function getName() { ... }
  function add(SitePart $part) { $this->parts[$part->name] = $part }
  function get($partName) { return $this->parts[$name] }
}

class Site extends Category {
  function Site($name) { ... }
}

For creating your hierarchy and pages :

Site
 Categ 1
  Page 1
  Categ 1.1
 Categ 2
$site = new Site();

$categ1 = new Category('Categ 1');
$categ11 = new Category('Categ 1.1');
$categ2 = new Category('Categ 2');

$site->add($categ1);
$site->add($categ2);
$categ1->add($categ11);

$categ1->add(new Page('Page 1','Hello world');

And now to retrieve page 1 for example :

$page = $site->get('Categ 1')->get('Page 1');
echo $page->getContent();

I hope that will help you.

Comments

0

If you need collection of objects, have a look at SplObjectStorage.

The SplObjectStorage class provides a map from objects to data or, by ignoring data, an object set. This dual purpose can be useful in many cases involving the need to uniquely identify objects.

Or, if you want a simple accessible tree structure, consider using SimpleXml. That wouldnt allow you to use custom page objects easily though. You dont seem to do much more with the page objects besides adding HTML to it, so it might be feasible in your case.

For more advanced needs, see the Composite Design pattern

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.