ucscode / tree-node
A versatile tool designed to simplify the management of parent-child relationships within a hierarchical structure
Requires
- php: >=8.1
Requires (Dev)
- phpunit/phpunit: ^10.5
README
The TreeNode
class is a versatile tool designed to simplify the management of parent-child relationships within a hierarchical structure. It is efficient in dealing with organizational charts, family trees, or any scenario involving hierarchical data and also provides an intuitive way to handle relationships.
Table of Contents
Introduction
Managing hierarchical relationships can be complex, especially when dealing with varying levels of parent-child connections. The TreeNode
class aims to streamline this process by providing methods to add relationships, retrieve children, and find ancestors within the hierarchy.
Installation
To use the TreeNode
class, follow these simple steps:
- Download the class file.
- Include the file in your project.
- Instantiate the class to start managing your hierarchical data.
For Composer Installation
composer require ucscode/tree-node
Usage
Creating Root Node
use Ucscode\TreeNode\TreeNode; $ceo = new TreeNode('Ucscode');
Creating Children
// Create Children with (or without) name & attribute $manager = new TreeNode('Elizabeth'); $staff = new TreeNode('Serena Paul', ['active' => true]); $staff2 = new TreeNode(null, ['name' => 'Unknown'])
Adding A Child
// Position each node under a dedicated parent $ceo->addChild('manager', $manager); $manager->addChild('staff', $staff); $manager->addChild('staff2', $staff2);
Getting A Child
$manager = $ceo->getChild('manager');
Removing A Child
$manager->removeChild('staff');
Getting Children
$manager->getChildren(); // Array of TreeNodes
Getting Ancestors
TreeNode also allows chaining
method.
$staff2 = $treeNode->getParent(); // Manager $ceo = $staff2 ->getParent() // Manager ->getParent(); // Ceo
Getting A Child Attribute
$staff2->getAttribute('name'); // "Unknown"
Setting A Child Attribute
$ceo->setAttribute('location', 'Log Angeles');
Removing A Child Attribute
$staff->removeAttribute('active');
Conclusion
The TreeNode
class provides a straightforward solution for handling hierarchical relationships. By offering methods to add relationships, retrieve children, and find ancestors, this class empowers developers to efficiently manage and navigate complex hierarchical structures in their applications. Simplify your hierarchical data management with the TreeNode
class today!