Implementing An N-Level Nested Tree In PHP And PostgreSQL, Part 2
Potential Class Improvements
The functionality implemented in this article is fairly simple, yet very powerful. There are many other additions you can implement to make the NestedTree class even more powerful.
I decided not to include these in our class, because they might cloud the general understanding and theory of implementing nested trees (in other words they are not core to the concept).
Anyway, here are a few examples. Consider them to be an exercise!
A custom row ordering system
In this implementation, we used a single field, ordering ascending, to sort the rebuilt tree data. You could build in extra functionality to sort of multiple fields, in the order you require (e.g. if you wanted to sort categorised news articles, you may want to sort them by their descending timestamp).
For phpRiot, we actually use a separate ranking system for each article within a section of the site. So instead of ordering the articles by their title, we actually order them by their “rank” (each article is numbered 1..n for n articles in a section). We have actually extended the phpRiot NestedTree class to incorporate functionality to rerank nodes (move up 1, move to top, move down 1, move to bottom).
More efficient tree building
Currently when you rebuild the tree, the n-values for every node are regenerated. This could be improved so you isolate only affect nodes and rebuild them. For example, if you delete a node (let’s say it has no children, or if it does then you deleted them first), this doesn’t affect the nlevel of any other node, so you don’t really need to update this in the database.
Or, if you implement a ranking system as suggested just previously, moving an article “up 1 place”, really only affects the n-values for the two articles being swapped (and their children articles if they exist), so really only those nodes need their n-values updated — not everything else in the tree.
Multiple trees in one table
On another site I have built, we store a large number of separate trees in the same table. Each client has their own tree of data, but one client’s tree is in no way related to another clients.
The way we solved this was to add filters to the NestedTree class. So whenever a query was made fetching the tree, the filter would be added something along the lines of “where client_id = $client_id”, which meant the other trees in the table were unaffected.
It is actually much simpler to do this than it seems.