Hello all,
I'm working on a directory browser (think Windows Explorer etc), and I'm at the stage of getting a list of folders under a root folder. I had this working before by placing folders in a large multi-dimensional array, but this got messy when it came to structuring it later. So then I tried a OO approach, using a Node object to represent a folder. Adding Nodes manually worked (nested nodes etc), but when it came to building the node list in a recursive method, it doesn't work. It doesn't seem like an impossible thing to do so can anyone point out where I'm going wrong?
class.Node.php
<?php
class Node {
var $name;
var $parent;
var $parentName;
var $children;
function Node($name) {
$this->name = $name;
$this->children = array();
}
function setParent($node) {
$this->parent = $node;
$this->parentName = $node->name;
}
function setChild($node) {
array_push($this->children, $node);
// echo "Size: ".sizeof($this->children)."<br>";
}
function printChildren() {
// echo "Root: ".$this->name."<br><blockquote";
for ($i=0; $i<sizeof($this->children); $i++) {
$tNode = $this->children[$i];
echo $tNode->name." (".sizeof($tNode->children).")<br>";
if ($tNode->hasChild()) {
echo "<blockquote>";
$tNode->printChildren();
echo "</blockquote>";
}
}
// echo "</blockquote<br>";
}
function hasChild() {
if (sizeof($this->children) >= 1)
return true;
else
return false;
}
function getChildren() {
return $this->children;
}
}
?>
And the other file (relevent sections):
<?php
require_once("class/class.Node.php");
$rootNode = new Node("Members");
$rootNode->setParent($rootNode);
$path = "/somewhere/to/something";
$rootNode = tree($rootNode, $path, 3);
echo "<p>";
$rootNode->printChildren();
$rCount = 0;
function tree($rootNode, $directory, $maxDepth = 5) {
global $rCount;
$currDepth = $rCount;
if ($currDepth <= $maxDepth) {
if ($handle = dir($directory)) {
while ($file = $handle->read()){
$nPath = $directory."/".$file;
if ($file != "." && $file != ".." && $file != "CVS" && is_dir($nPath)) {
$tNode = new Node($file);
$tNode->setParent($rootNode);
$rootNode->setChild($tNode);
echo $directory."/".$file.", Node: ".$tNode->name.", parent: ".$tNode->parentName."<br>";
echo "(ROOT) name: ". $rootNode->name ." parent: ".$rootNode->parentName."<br>";
$rootNode->printChildren();
$rCount ++;
tree(&$tNode, $directory."/".$file, $maxDepth);
}
}
}
}
return ($rootNode);
}
?>
(note: recursion control probably doesn't work, so you may want to try that at your own risk 😉 )
Ideally when the printChildren() is called from the rootNode, it should print out a nicely indented list of all the subfolders under the root. At the moment, the rootNode doesn't seem to be storing the childNodes that are more than 1 directory deep, only the first level. ie. Output:
/Root/Dir1 (0)
/Root/Dir2 (0)