Tree implementation for hierarchical accounts in Prophit

dev-main 2022-12-30 14:09 UTC

This package is auto-updated.

Last update: 2023-08-29 02:51:04 UTC


Tree implementation for hierarchical accounts in Prophit.

Released under the MIT License.


composer require prophit/account-tree


prophit/core provides an Account entity class for accounts, but it has no sense of accounts forming a hierarchy.


use Prophit\Core\Account\Account;

$account = new Account(

This library extends that Account class to support the notion of parent-child relationships between accounts. To do so, it adds a constructor parameter $parentId, which should take on the value of the $id property of the Account instance corresponding to the parent account.


use Prophit\AccountTree\Account;

// The $parentId constructor parameter is not specified here and defaults to null,
// which is used to indicate that the account does not have a parent.
$parentAccount = new Account('PARENT-ID', 'Parent Account');

// The $parentId constructor parameter is specified here to indicate that this
// account is a child of the above parent account.
$childAccount = new Account('CHILD-ID', 'Child Account', $parentAccount->getId());

// The $parentId constructor parameter is specified here to indicate that this
// account is a child of the above child account.
$grandchildAccount = new Account('GRANDCHILD-ID', 'Grandchild Account', $childAccount->getId());


prophit/core provides an AccountIterator class to represent an iterable group of accounts.


use Prophit\Core\Account\{Account, AccountIterator};

$account1 = new Account('1', 'Account 1');
$account2 = new Account('2', 'Account 2');
$iterator = new AccountIterator($account1, $account2);

This library provides an AccountTree class, which takes an instance of AccountIterator as its only constructor parameter. AccountTree is iterable and uses loophp/phptree under the hood to perform a pre-order traversal of the accounts.

When AccountTree iterates over an account, it returns an instance of that account with an additional property populated to represent the depth of the account within the tree. This depth can be retrieved using the getDepth() method of the account instance.

These features together are useful for rendering an account list visualized as a tree within a user interface.


// From the earlier example:
// $parentAccount = ...
// $childAccount = ...
// $grandchildAccount = ...

use Prophit\Core\Account\AccountIterator;
use Prophit\AccountTree\AccountTree;

$iterator = new AccountIterator(

$tree = new AccountTree($iterator);
foreach ($tree as $account) {
    echo str_repeat('  ', $account->getDepth()), $account->getName(), PHP_EOL;

// Output:
// Parent Account
//   Child Account
//     Grandchild Account