How can PHP developers efficiently store and retrieve hierarchical data structures like directory trees?

Storing and retrieving hierarchical data structures like directory trees can be efficiently done using nested sets model in PHP. This model involves assigning left and right values to nodes in the tree to represent the parent-child relationships. With this approach, querying and manipulating the hierarchical data becomes more efficient.

// Sample code snippet for storing and retrieving hierarchical data using nested sets model

class NestedSets {
    private $pdo;

    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
    }

    public function createNestedSetTable() {
        $this->pdo->exec('CREATE TABLE nested_sets (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(255) NOT NULL,
            lft INT NOT NULL,
            rgt INT NOT NULL
        )');
    }

    public function insertNode($name, $parentId = null) {
        // Insert node into nested sets table based on parent node
    }

    public function retrieveTree() {
        // Retrieve hierarchical data using nested sets model
    }
}

// Example usage
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$nestedSets = new NestedSets($pdo);
$nestedSets->createNestedSetTable();
$nestedSets->insertNode('Root');
$nestedSets->insertNode('Child 1', 1);
$nestedSets->insertNode('Child 2', 1);
$nestedSets->insertNode('Grandchild 1', 2);
$nestedSets->insertNode('Grandchild 2', 2);
$tree = $nestedSets->retrieveTree();