vakata/phptree

A collection of PHP classes for storing a tree in a relational database

3.2.1 2024-11-12 15:29 UTC

This package is auto-updated.

Last update: 2024-12-12 15:36:52 UTC


README

Latest Version on Packagist Software License Build Status Code Climate Tests Coverage

Storing trees in a relational database. Keep in mind the tree needs to have a single root, so it is probably safe to begin with this structure (this example is mySQL, but it should be clear):

CREATE TABLE struct (
    id  int(10) unsigned NOT NULL AUTO_INCREMENT,
    lft int(10) unsigned NOT NULL,
    rgt int(10) unsigned NOT NULL,
    lvl int(10) unsigned NOT NULL,
    pid int(10) unsigned NOT NULL,
    pos int(10) unsigned NOT NULL,
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO struct VALUES (1, 1, 2, 0, 0, 0);

# now you can use 1 as your tree root

Install

Via Composer

$ composer require vakata/phptree

Usage

// create an instance
$dbc = new \vakata\database\DB("mysqli://root@127.0.0.1/treedb");
$tree = new \vakata\phptree\Tree(
    $dbc,
    'tree_table',
    [ 'id' => 'id', 'parent' => 'pid', 'position' => 'pos', 'level' => 'lvl', 'left' => 'lft', 'right' => 'rgt' ]
);

// WORKING WITH NODES
$tree->getRoot()->getChildren(); // get all children of the root

$tree->getRoot()->addChild(new \vakata\phptree\Node(['key' => 'val1'])); // create a node
$tree->getRoot()->addChild(new \vakata\phptree\Node(['key' => 'val2'])); // create a node
$tree->save();
$tree->getNode(2)->moveTo($tree->getRoot(), 2);
$tree->getNode(3)->copyTo($tree->getRoot());
$tree->getNode(3)->remove();

Read more in the API docs

Testing

$ composer test

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email github@vakata.com instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.