Quantcast
Viewing all articles
Browse latest Browse all 10

Dynamic Menu Builder for Bootstrap 3: Item and Link

In part 1, we prototyped the end product and wrote the main Menu class, which serves as the menu manager – a container to hold all sub-units (items and links). In this part, we’ll build the remainder of the classes and demonstrate the menu builder’s usage.

Item

Represents our menu items as independent objects.

Create a new file called item.php and paste in the following code:

item.php

<?php
class Item {

    protected $manager;
    protected $id;
    protected $pid;
    protected $meta;
    protected $attributes = array();

    public    $link;

    //...
?>
  • $manager stores a reference to the menu manager (Menu object). This makes us able to use menu manager methods within Item context.
  • $id stores the item’s id.
  • $pid stores item’s parent id if it has one otherwise it’ll be set to null.
  • $meta an array for storing extra data with each item.
  • $attributes an array of HTML attributes.
  • $link stores an instance of class Link.

__construct(manager, title, url, attributes, pid)

Initializes the attributes.

<?php
public function __construct($manager, $title, $url, $attributes = array(), $pid = 0)
{
    $this->manager     = $manager;
    $this->id          = $this->id();
    $this->pid         = $pid;
    $this->title       = $title;
    $this->attributes  = $attributes;

    // Create an object of type Link
    $this->link        = new Link($title, $url);
}
?>

add(title, options)

Class Item has an add() method as well (just like the menu manager). In fact this method doesn’t create items on its own. It gets the arguments, adds a pid key to $options and calls add() of the menu manager.

<?php
public function add($title, $options)
{
    if( !is_array($options) ) {
            $options = array('url' => $options);
        }

    $options['pid'] = $this->id;

    return $this->manager->add( $title, $options );
}
?>

This gives us the power to create sub items in a more semantic way rather than explicitly defining a pid:

<?php
    $menu = new Menu;

    $about = $menu->add('About', 'about');

    // We write it this way
    $about->add('What we do?', 'what-we-do');

    // instead of:
    // $menu->add('What we do?', array('url' => 'what-we-do', 'pid' => $about->get_id()));
?>

id()

Generates a unique id for the Item. We use this identifier to refer to the item later.

Continue reading %Dynamic Menu Builder for Bootstrap 3: Item and Link%

View full post on SitePoint


Viewing all articles
Browse latest Browse all 10

Trending Articles