PhpRiot
Download This Article
Download this article or the entire “Implementing An N-Level Nested Tree In PHP And PostgreSQL” series with all listings and files.




More information
Related Books
Professional Linux Programming

Professional Linux Programming

As Linux increases its presence throughout the world as a target platform for professional...
Browse Articles
Ajax (4), APC (1), CAPTCHA (1), CSS (3), Debugging (1), File Upload (1), Google (3), Google Maps (2), JavaScript (12), JSON (2), MVC (1), MySQL (7), onbeforeunload (1), OOP (1), PHP (28), PhpDoc (1), PostgreSQL (6), Prototype (11), Reflection (1), RFC 1867 (1), Robots (1), Scriptaculous (1), SEO (1), Sessions (1), SimpleXML (1), Smarty (5), SOAP (1), SPL (1), Templates (2), W3C (1), XHTML (1), Zend Framework (1), Zend_Search_Lucene (1)

PhpRiot Newsletter
Your Email Address:

Implementing An N-Level Nested Tree In PHP And PostgreSQL, Part 2

Designing The Class

We must now design the class. We will be calling the class NestedTree.

There are several key requirements in designing the class, including:

  • We must be able to easily use it on any table
  • If we have more than one table in our database that uses a tree we should be able to reuse the class for both
  • Aside from the necessary tree data (e.g. nleft, nright, etc.), we must be able to store any other amount of arbitrary data in our database table if required.

One of the key things to remember is, the point behind this class is to handle manipulation of tree data — because we want to deal with arbitrary data in our table, this class does not deal with inserting or deleting of data from the tree per se. Rather, it provides functionality to maintain the structural metadata and extract data quickly.

For example, the article data for PhpRiot is inserted into the database using our Article class. When a record is inserted, updated or deleted with the Article class, the class invokes the NestedTree class to maintain the tree data for the articles table.

Functionality

There are a core set of functions we need to extract data from the data:

  • Fetch a single node
  • Fetch various portions of the tree (e.g. the whole tree, a node’s children, a node’s descendants)
  • Fetch a node’s children
  • Fetch the path to a node

We need functions to build the tree:

  • Calculate the nleft / nright / nlevel values
  • Write the tree data to the database

And some utility functions:

  • Check if a node descends from another node
  • Check if a node is a child of another node
  • Find the number of children or descendants a node has

In This Article


Tagged in , ,