What are best practices for structuring and organizing PHP code to handle hierarchical data like user relationships?

When dealing with hierarchical data like user relationships in PHP, it is best to use a recursive approach to handle the relationships effectively. One common way to structure and organize the code is to create a User class that contains methods for retrieving and manipulating user relationships. By using recursive functions, you can easily traverse the user hierarchy and perform actions such as getting all descendants of a user or finding the ancestors of a user.

class User {
    public $id;
    public $name;
    public $children = [];

    public function __construct($id, $name) {
        $this->id = $id;
        $this->name = $name;
    }

    public function addChild(User $child) {
        $this->children[] = $child;
    }

    public function getDescendants() {
        $descendants = [];
        foreach ($this->children as $child) {
            $descendants[] = $child;
            $descendants = array_merge($descendants, $child->getDescendants());
        }
        return $descendants;
    }

    public function getAncestors() {
        $ancestors = [];
        // logic to find ancestors
        return $ancestors;
    }
}

// Example usage
$user1 = new User(1, 'Alice');
$user2 = new User(2, 'Bob');
$user3 = new User(3, 'Charlie');

$user1->addChild($user2);
$user2->addChild($user3);

$descendants = $user1->getDescendants();
print_r($descendants);