HomePHP Page 4 - Building an Extensible Menu Class
Children And Their Parents - PHP
So you know the theory behind OOP, but don't really understandits applications? Well, it's time to take objects out of the classroom andinto the real world - this article demonstrates how OOP can save you timeand effort by building a PHP-based Menu object to describe therelationships in a hierarchical menu tree. And since the proof of thepudding is in the eating, it then combines the newly-minted Menu objectwith some of the most popular JavaScript menu systems available online toshow you how cool objects really are.
Now, the Menu object that I plan to build actually consists of two components: a database, and a series of functions to interact with it. The database contains all the raw data needed to generate the menu tree, while the class contains all the functions needed to massage the data into a useful format.
I plan to use a very simple mySQL table to store all my menu information, as well as the relationships between the various levels of the tree - take a look:
#
# Table structure for table 'menu'
#
DROP TABLE IF EXISTS menu;
CREATE TABLE menu (
id tinyint(3) unsigned NOT NULL auto_increment,
label varchar(255) NOT NULL,
link varchar(255),
parent tinyint(3) unsigned DEFAULT '0' NOT NULL,
PRIMARY KEY (id)
);
#
# id - unique identifier for each node
# label - descriptive text for each node
# link - URL for each node
# parent - id of this node's parent
#
This design makes it easy to represent a hierarchical menu
tree in terms of database records. For example, I could represent the following visual tree
USA
|
| -- California
|
| -- Los Angeles
|
| -- Massachusetts
|
| -- Boston
United Kingdom
|
| -- London
as a series of records in the "menu" table.
mysql> SELECT * FROM menu;
+----+------+----------------+--------+
| id | link | label | parent |
+----+------+----------------+--------+
| 1 | | USA | 0 |
| 2 | | California | 1 |
| 3 | | Los Angeles | 2 |
| 4 | | Massachusetts | 1 |
| 5 | | Boston | 4 |
| 6 | | United Kingdom | 0 |
| 7 | | London | 6 |
+----+------+----------------+--------+
7 rows in set (0.00 sec)