Building an Extensible Menu Class - Collapsing Inwards (
Page 9 of 10 )
If you go back
a few pages, you'll notice that one of the design goals of this Menu object was
to separate the visual presentation of a menu from the relationships between the
various nodes. I've already demonstrated how the same Menu object can be used to
create a directory and a hierarchical menu tree with standard methods.
My
third example is similar to the second, again connecting a JavaScript-based menu
system to the menu database to dynamically build a menu tree. For this, I plan
to use another very popular menu constructor, FolderTree (free version available
at http://www.geocities.com/marcelino_martins/foldertree.html ), which uses
Windows Explorer-style files and folders to display a hierarchy of
items.
First, I need an HTML page to invoke FolderTree and display the
menu:
<html>
<head>
<basefont face="Arial">
<link rel="stylesheet" href="ftie4style.css">
<!-- Infrastructure code for the tree -->
<script src="ftiens4.js"></script>
<!-- Execution of the code that actually builds the specific tree -->
<script src="menu.js.php"></script>
<script>
initializeDocument()
</script>
</head>
<body bgcolor=white>
</body>
</html>
As you can see, this file sources "menu.js.php", which
contains the actual menu data. This file is usually created manually as per the
user's requirements; I plan to hook it up to my database table to generate it
dynamically. Here's the code:
// menu.js.php
// set up tree root
foldersTree = gFld("Melonfire", "http://www.melonfire.com");
<?
// initialize object
include("menu.class.php");
$obj = new Menu();
// counter - used to create tree nodes
$count = 0;
function buildMenu($id, $node)
{
global $obj;
global $count;
// get children
$children = $obj->get_children($id);
for ($x=0; $x<sizeof($children); $x++)
{
// write the name of this node
$newNode = "aux" . $count;
// if folder
if($obj->get_type($children[$x]["id"]) == 1)
{
// call appropriate FolderTree function to display folder icon
$count++;
$str = $newNode . " = insFld(" . $node . ", gFld(\"" .
$children[$x]['label'] . "\", \"" . $children[$x]['link'] . "\"));";
print $str;
// and recurse for next level
buildMenu($children[$x]["id"], $newNode);
}
else
{
// if last level
// call appropriate FolderTree function to display file icon
$str = "insDoc(" . $node . ", gLnk(2, \"" . $children[$x]['label'] . "\",
\"" . $children[$x]['link'] . "\"));";
print $str;
}
}
}
// initiate recursive function
buildMenu(0, "foldersTree");
?>
You just gotta love those recursive functions!
Here's
what it all looks like: