Render a datatree structure
Thinktomorrow\Vine
is a PHP package designed to manage and manipulate adjacent tree-structured models. It provides a powerful interface for building and querying collections of hierarchical data, with methods to traverse, sort, and manipulate node collections in a flexible way., (*1)
It's key features are: - Tree Traversal: Map and traverse nodes with recursion. - Manipulation: Add, remove, or merge nodes. - Flattening & Inflating: Convert hierarchical data to flat lists and vice versa. - Customizable Queries: Find nodes based on specific attributes., (*2)
IMPORTANT
An adjacent tree structure is assumed, where each node has an id
and parent_id
attribute., (*3)
Install the package via composer:, (*4)
composer require thinktomorrow/vine
You can create a node collection from an array of nodes., (*5)
use Thinktomorrow\Vine\NodeCollection; use Thinktomorrow\Vine\Node; // Assuming Node is a model implementing the Node interface $nodes = [ new Node(['id' => 1, 'name' => 'Parent']), new Node(['id' => 2, 'name' => 'Child', 'parent_id' => 1]) ]; $collection = NodeCollection::fromArray($nodes);
The package allows you to iterate over nodes recursively., (*6)
$collection->eachRecursive(function($node) { echo $node->getName(); // Access node attributes });
To get a flat array of all nodes:, (*7)
$flatNodes = $collection->flatten()->toArray();
You can restore a flattened collection back to its tree structure:, (*8)
$inflatedCollection = $collection->inflate();
To find nodes by specific attributes:, (*9)
$node = $collection->find('id', 1); // Find a node with id = 1
Or find multiple nodes by a set of values:, (*10)
$nodes = $collection->findMany('id', [1, 2, 3]); // Find nodes with ids 1, 2, and 3
You can add or merge nodes into the collection:, (*11)
$newNode = new Node(['id' => 3, 'name' => 'New Child']); $collection->add($newNode); // Add a new node $otherCollection = NodeCollection::fromArray([...]); // Another node collection $collection->merge($otherCollection); // Merge collections
Nodes can be sorted by any attribute:, (*12)
$sortedCollection = $collection->sort('name'); // Sort by 'name' attribute
To remove nodes by attribute or condition:, (*13)
$collection = $collection->remove(function($node) { return $node->getId() == 2; // Remove node with id 2 });
use Thinktomorrow\Vine\NodeCollection; use Thinktomorrow\Vine\Node; $nodes = [ new Node(['id' => 1, 'name' => 'Root']), new Node(['id' => 2, 'name' => 'Child 1', 'parent_id' => 1]), new Node(['id' => 3, 'name' => 'Child 2', 'parent_id' => 1]) ]; $collection = NodeCollection::fromArray($nodes); // Add a node $collection->add(new Node(['id' => 4, 'name' => 'New Child', 'parent_id' => 2])); // Flatten, sort, and remove $flatNodes = $collection->flatten()->sort('name')->remove(function($node) { return $node->getName() === 'Child 2'; }); // Output as array print_r($flatNodes->toArray());