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/nlevelvalues - 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


