Home arrow PHP arrow Page 5 - Building an Extensible Menu Class

I Say Method, You Say Madness... - 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.

  1. Building an Extensible Menu Class
  2. Back To Class
  3. What's On The Menu?
  4. Children And Their Parents
  5. I Say Method, You Say Madness...
  6. Rounding Up The Family
  7. Saving My Bookmarks
  8. Reaching Higher
  9. Collapsing Inwards
  10. Extending Yourself
By: Team Melonfire, (c) Melonfire
Rating: starstarstarstarstar / 6
August 10, 2001

print this article


With the database design out of the way, it's now time to begin work on the methods which will interact with the records in the database. Before actually sitting down to code the class, it's a good idea to spend some time listing the important methods, together with their purpose. Here's my initial cut:

query($query) - execute an SQL query;

get_children($node) - return a collection of this node's children;

get_parent($node) - return the identifier of this node's parent;

get_label($node) - return the name of this node

get_type($node) - return the node type (leaf or branch)

is_root_node($node) - is this node at the root level or not?

These are the essential methods; there may be more, which I will add as development progresses.

Let's now begin by setting up the class definition:

<? // menu.class.php // methods to obtain node and tree relationships class Menu { } ?><hr noshade size=1 color=#cccccc></pre></blockquote> Now, since this class will be talking to a database, I need to add a few variables to hold database-specific information. <blockquote><pre><hr noshade size=1 color=#cccccc><? class Menu { // set up some variables with default values // to hold database parameters // hostname, user and password var $hostname; var $user; var $pass; // database and table containing menu data var $db; var $table; } ?>
PHP makes it possible to automatically execute a specific function when a new instance of a class is spawned. This function is referred to as a "constructor" and must have the same name as the class.

In this case, I plan to initialize my Menu object with certain default values for the various database parameters. I have the option of assigning these variable-value pairs individually, or writing a method to assign them all in one fell swoop; I pick the latter.

<? class Menu { // set up some variables // snip // constructor function Menu() { $this->set_database_parameters("localhost", "me", "bs49h5634", "apps", "menu"); } // function: set database parameters // returns: none function set_database_parameters($hostname, $user, $password, $db, $table) { $this->hostname = $hostname; $this->user = $user; $this->password = $password; $this->db = $db; $this->table = $table; } } ?>
In case you're wondering, the $this prefix provides a convenient way to access variables and functions which are "local" to the class

Now, all the methods listed above will be querying the database for information. Since the connect-and-query code is common to all of them, I can extract it into a separate method named query().

<? class Menu { // other methods // function: execute query $query // returns: result identifier function query($query) { // connect $connection = mysql_connect($this->hostname, $this->user, $this->pass) or die ("Cannot connect to database"); // run query $ret = mysql_db_query($this->db, $query, $connection) or die ("Error in query: $query"); // return result identifier return $ret; } } ?>
All my object methods can now simply use query() to execute SQL queries on the database. Further - if I ever decide to move to another database, I need only update the code in this single function to ensure that my class will continue to work with the new system.{mospagebreak title=Playing With Nodes} With the underlying, database-specific layer in place, I can now begin work on the main object methods. The first of these is also one of the simplest - it accepts a node id and returns the id of the node's parent.

<? class Menu { // other methods // function: get parent // returns: node id function get_parent($id) { $query = "SELECT parent FROM $this->table WHERE id = '$id'"; $result = $this->query($query); $row = mysql_fetch_row($result); return $row[0]; } } ?>
An offshoot of this is the is_root_node() method, used to test whether a particular node is at the base of the menu tree.

<? class Menu { // other methods // function: is this node at the root of the tree? // returns: boolean function is_root_node($id) { if($this->get_parent($id) == 0) { return 1; } else { return 0; } } } ?>
The get_label() and get_link() methods accept a node id and return the corresponding text and URL from the table.

<? class Menu { // other methods // function: get label for $id // returns: string function get_label($id) { $query = "SELECT label FROM $this->table WHERE id = '$id'"; $result = $this->query($query); $row = mysql_fetch_row($result); return $row[0]; } // function: get link for $id // returns: string function get_link($id) { $query = "SELECT link FROM $this->table WHERE id = '$id'"; $result = $this->query($query); $row = mysql_fetch_row($result); return $row[0]; } } ?>
Using the menu table constructed a few pages ago, the code

<? $obj = new Menu(); echo $obj->get_label(3); ?>
would return

Los Angeles

>>> More PHP Articles          >>> More By Team Melonfire, (c) Melonfire

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: