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.
在第1部分中,我们对最终产品进行了原型设计,并编写了主Menu类,该类用作菜单管理器–一个容纳所有子单元(项目和链接)的容器。 在这一部分中,我们将构建其余的类,并演示菜单构建器的用法。
项目 (Item)
Represents our menu items as independent objects.
将我们的菜单项表示为独立的对象。
Create a new file called item.php
and paste in the following code:
创建一个名为item.php
的新文件,并粘贴以下代码:
item.php
item.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 withinItem
context.$manager
存储对菜单管理器(Menu
对象)的引用。 这使我们能够在Item
上下文中使用菜单管理器方法。$id
stores the item’s id.$id
存储项目的ID。$pid
stores item’s parent id if it has one otherwise it’ll be set tonull
.$pid
存储项目的父ID(如果有的话),否则将设置为null
。$meta
an array for storing extra data with each item.$meta
一个数组,用于存储每个项目的额外数据。$attributes
an array of HTML attributes.$attributes
分配HTML属性数组。$link
stores an instance of classLink
.$link
存储类Link
的实例。
__construct(管理员,标题,URL,属性,PID) (__construct(manager, title, url, attributes, pid))
Initializes the attributes.
初始化属性。
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.
类Item
也具有add()
方法(就像菜单管理器一样)。 实际上,此方法不会自行创建项目。 它获取参数,将pid
键添加到$options
并调用菜单管理器的add()
。
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
:
这使我们能够以更语义的方式创建子项,而不是显式定义pid
:
$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() (id())
Generates a unique id for the Item. We use this identifier to refer to the item later.
生成项目的唯一ID。 我们稍后使用此标识符来引用该项目。
protected function id()
{
return $this->manager->length() + 1;
}
In fact
id()
callslength()
of the menu manager and increments it by 1.实际上,
id()
调用菜单管理器的length()
并将其递增1。
get_id() (get_id())
We also need to create a getter method to return the id when needed:
我们还需要创建一个getter方法来在需要时返回id:
public functi