PHPackages                             tobento/service-treeable - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. tobento/service-treeable

ActiveLibrary

tobento/service-treeable
========================

Building trees easily.

2.0(5mo ago)11681MITPHPPHP &gt;=8.4

Since Jun 13Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/tobento-ch/service-treeable)[ Packagist](https://packagist.org/packages/tobento/service-treeable)[ Docs](https://www.tobento.ch)[ RSS](/packages/tobento-service-treeable/feed)WikiDiscussions 2.x Synced today

READMEChangelog (3)Dependencies (2)Versions (5)Used By (1)

Treeable Service
================

[](#treeable-service)

With the Treeable Service you can create and manipulating trees easily.

Table of Contents
-----------------

[](#table-of-contents)

- [Getting started](#getting-started)
    - [Requirements](#requirements)
    - [Highlights](#highlights)
- [Documentation](#documentation)
    - [Array Tree](#array-tree)
    - [Tree](#tree)
    - [Traverser](#traverser)
- [Credits](#credits)

---

Getting started
===============

[](#getting-started)

Add the latest version of the Treeable service project running this command.

```
composer require tobento/service-treeable

```

Requirements
------------

[](#requirements)

- PHP 8.4 or greater

Highlights
----------

[](#highlights)

- Framework-agnostic, will work with any project
- Decoupled design

Documentation
=============

[](#documentation)

Array Tree
----------

[](#array-tree)

Array tree creates the following data structure:

```
use Tobento\Service\Treeable\ArrayTree;

$items = [
    [
        'name' => 'cars',
    ],
    [
        'name' => 'VW',
        'parent' => 'cars',
    ],
];

$items = (new ArrayTree($items, 'name', 'parent'))->create();

Array
(
    [cars] => Array
        (
            [name] => cars
            [parent] =>
            [level] => 0
            [parentItem] =>
            [children] => Array
                (
                    [VW] => Array
                        (
                            [name] => VW
                            [parent] => cars
                            [level] => 1
                            [parentItem] => Array
                                (
                                    [name] => cars
                                    [parent] =>
                                    [level] => 0
                                    [parentItem] =>
                                )

                        )

                )

        )

)
```

Change the item keys for your array needs.

```
use Tobento\Service\Treeable\ArrayTree;

$tree = new ArrayTree($items, 'id', 'parent_id', 'level', 'children', 'parentItem');
```

### Sorting the array items.

[](#sorting-the-array-items)

```
use Tobento\Service\Treeable\ArrayTree;

// sort by array key.
$items = new ArrayTree($items, 'name', 'parent')->sort('name')->create();

// sort by callable.
$items = new ArrayTree($items, 'name', 'parent')
    ->sort(fn ($a, $b) => $a['name']  $b['name'])
    ->create();
```

### Filter the array items.

[](#filter-the-array-items)

```
use Tobento\Service\Treeable\ArrayTree;

$items = new ArrayTree($items, 'name', 'parent')
    ->filter(fn($i) => $i['name'] === 'cars')
    ->create();
```

### Iterating over the array items.

[](#iterating-over-the-array-items)

On the each() method, the tree data structure has already been build, so you may use this information.

```
use Tobento\Service\Treeable\ArrayTree;

$items = new ArrayTree($items, 'name', 'parent')
    ->each(function($item, $level) {

        if ($level >= 1) {
            return null;
        }

        $parentItem = $item['parentItem'];

        return $item;
    })
    ->create();
```

### Iterating over the parent array items from a specific tree item.

[](#iterating-over-the-parent-array-items-from-a-specific-tree-item)

```
use Tobento\Service\Treeable\ArrayTree;

$items = new ArrayTree($items, 'name', 'parent')
    ->parents('BMW', function($item) {
        $item['active'] = true;
        return $item;
    })
    ->create();
```

Tree
----

[](#tree)

Using the Tree class, items must implement the Treeable interface.

```
use Tobento\Service\Treeable\Tree;
use Tobento\Service\Treeable\Treeable;
use Tobento\Service\Treeable\TreeableAware;

/**
 * Item
 */
class Item implements Treeable
{
    use TreeableAware;

    /**
     * Create a new Item
     *
     * @param string
     * @param null|string
     */
    public function __construct(
        protected string $text,
        protected ?string $parent = null,
    ) {}

    /**
     * Get the tree id
     *
     * @return string|int
     */
    public function getTreeId(): string|int
    {
        return $this->text;
    }

    /**
     * Get the tree parent
     *
     * @return null|string|int
     */
    public function getTreeParent(): null|string|int
    {
        return $this->parent;
    }

    public function text(): string
    {
        return $this->text;
    }
}

$tree = new Tree([
    new Item('cars'),
    new Item('VW', 'cars'),
    new Item('BMW', 'cars'),
]);

$items = $tree->create();
```

### Sorting items

[](#sorting-items)

```
use Tobento\Service\Treeable\Tree;

$tree = new Tree([
    new Item('cars'),
    new Item('VW', 'cars'),
    new Item('BMW', 'cars'),
]);

$tree->sort(fn ($a, $b) => $a->text()  $b->text());

$items = $tree->create();
```

### Filtering items

[](#filtering-items)

```
use Tobento\Service\Treeable\Tree;

$tree = new Tree([
    new Item('cars'),
    new Item('VW', 'cars'),
    new Item('BMW', 'cars'),
]);

$tree->filter(fn($i) => $i->text() === 'cars');

$items = $tree->create();
```

### Iterating over each item

[](#iterating-over-each-item)

On the each() method, the tree data structure has already been build, so you may use this information.

```
use Tobento\Service\Treeable\Tree;

$tree = new Tree([
    new Item('cars'),
    new Item('VW', 'cars'),
    new Item('BMW', 'cars'),
]);

$tree->each(function($item, $level) {
    if ($level >= 1) {
        return null;
    }

    //$item->getTreeLevel();

    return $item;
});

$items = $tree->create();
```

### Iterating over the parent items from a specific tree item.

[](#iterating-over-the-parent-items-from-a-specific-tree-item)

```
use Tobento\Service\Treeable\Tree;

$tree = new Tree([
    new Item('cars'),
    new Item('VW', 'cars'),
    new Item('BMW', 'cars'),
]);

$tree->parents('VW', function($item) {
    $item->active(true);
    return $item;
});

$items = $tree->create();
```

Traverser
---------

[](#traverser)

Traverse over array tree items.

```
use Tobento\Service\Treeable\Traverser;
use Tobento\Service\Treeable\ArrayTree;

$items = [
    [
        'name' => 'cars',
    ],
    [
        'name' => 'VW',
        'parent' => 'cars',
    ],
    [
        'name' => 'BMW',
        'parent' => 'cars',
    ],
];

$tree = new ArrayTree($items, 'name', 'parent');

// change the children key if needed.
$html = new Traverser($tree->create(), 'children')
    ->before(function($level) {
        return '';
    })
    ->item(function($item, $childrenHtml, $level) {

        if (!empty($childrenHtml)) {
            return ''.$item['name'].$childrenHtml.'';
        }

        return ''.$item['name'].'';
    })
    ->after(function($level) {
        return '';
    })
    ->render();
```

```

    cars

            VW
            BMW

```

Traverse over treeable items.

```
use Tobento\Service\Treeable\Traverser;
use Tobento\Service\Treeable\Tree;

$tree = new Tree([
    new Item('cars'),
    new Item('VW', 'cars'),
    new Item('BMW', 'cars'),
]);

$html = new Traverser($tree->create())
    ->before(function($level) {
        return '';
    })
    ->item(function($item, $childrenHtml, $level) {

        if (!empty($childrenHtml)) {
            return ''.$item->text().$childrenHtml.'';
        }

        return ''.$item->text().'';
    })
    ->after(function($level) {
        return '';
    })
    ->render();
```

```

    cars

            VW
            BMW

```

Credits
=======

[](#credits)

- [Tobias Strub](https://www.tobento.ch)
- [All Contributors](../../contributors)

###  Health Score

45

—

FairBetter than 93% of packages

Maintenance70

Regular maintenance activity

Popularity15

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~391 days

Total

5

Last Release

178d ago

Major Versions

1.x-dev → 2.02025-09-25

PHP version history (2 changes)1.0.0PHP &gt;=8.0

2.0PHP &gt;=8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/055d6a1b5c2384bb179c75ab0b55914231d898fdc4dffeb30770f81200e52206?d=identicon)[TOBENTOch](/maintainers/TOBENTOch)

---

Top Contributors

[![tobento-ch](https://avatars.githubusercontent.com/u/16684832?v=4)](https://github.com/tobento-ch "tobento-ch (17 commits)")

---

Tags

packagetreearray treetobento

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tobento-service-treeable/health.svg)

```
[![Health](https://phpackages.com/badges/tobento-service-treeable/health.svg)](https://phpackages.com/packages/tobento-service-treeable)
```

###  Alternatives

[efureev/laravel-trees

Multi-Tree structures for Laravel

14252.5k3](/packages/efureev-laravel-trees)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
