Yii2 Nested Sets
A nested sets behavior for Yii 2 ActiveRecord using the Modified Preorder Tree Traversal algorithm.
Repository Health
Technical Analysis
Yii2 Nested Sets (creocoder/yii2-nested-sets) is a Yii 2 framework extension that adds nested sets tree behavior to ActiveRecord models. It implements the Modified Preorder Tree Traversal (MPTT) algorithm, letting you store hierarchical data such as categories, menus, and comment threads in a single table while reading entire subtrees with fast, join-free queries.
Attached as a behavior, it augments your models with methods to append, prepend, insert before or after, and move nodes, and it ships a companion query behavior for retrieving roots, leaves, and ordered trees. It supports both single-tree and multiple-tree tables and integrates cleanly with Yii’s ActiveRecord and migration tooling.
What You Get
- A NestedSetsBehavior that attaches MPTT tree operations to any ActiveRecord model
- A NestedSetsQueryBehavior for retrieving roots, leaves, and ordered trees
- Node operations: makeRoot, prependTo, appendTo, insertBefore, insertAfter, and delete
- Support for both single-tree and multiple-tree tables via a tree attribute
- Clean integration with Yii 2 migrations and ActiveRecord relations
Common Use Cases
- Storing nested product or content categories with fast subtree reads
- Building hierarchical navigation menus of arbitrary depth
- Modeling threaded comments or organizational hierarchies
- Reordering and moving branches of a tree without recursive updates
Under The Hood
Architecture - The extension is two classes under the creocoder\nestedsets namespace: NestedSetsBehavior, which attaches to an ActiveRecord and manages the lft/rgt boundary columns (plus optional depth and tree), and NestedSetsQueryBehavior, which augments ActiveQuery with roots() and leaves() scopes. Node mutations shift boundary values within a transaction so the tree invariants hold after every insert, move, or delete.
Tech Stack - Built for Yii 2 (yiisoft/yii2 ~2.0), pure PHP with no other runtime dependencies. It relies on Yii’s ActiveRecord, behaviors, and events, and expects a schema created via standard Yii migrations. Tests use PHPUnit 4 with dbunit against MySQL.
Code Quality - The codebase is small, focused, and battle-tested, with a dedicated test suite covering both the behavior and query behavior against a real database. It has been stable for years with strong community adoption (high fork and watcher ratios), though active development has effectively stopped.
API Design - The behavior API reads naturally: makeRoot(), appendTo($node), prependTo($node), insertBefore/insertAfter($node), and children()/parents() traversal. Because it plugs in as a Yii behavior, adopting it requires only attaching the behavior and adding the boundary columns, keeping the learning curve modest for Yii developers.