tags:

views:

51

answers:

3

Hi everyone,

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?

Can anyone help guide me in the right direction please?

Thanks!

+1  A: 

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.

Krevan
A: 

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

Gordon
+1  A: 

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.

Mr_Qqn