简单的CI面包屑
2014-11-06 15:50
CodeIgniter
PHP
面包屑
摘要:写了一个简单的 CodeIgniter 面包屑组件,代码不复杂但够实用,分享一下实现思路。
面包屑是很常用的一种小功能,下面有一种十分简单的面包屑写法。
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* CI面包屑
*/
class Breadcrumb {
// 分隔符, 分隔符须有空格
public $link_type = ' > ';
public $breadcrumb = array();
public $output = '';
/**
* 清空面包屑
*/
public function clear() {
$props = array('breadcrumb', 'output');
foreach($props as $val) {
// 清空
$this->$val = null;
}
return true;
}
/**
* 添加一个面包屑
* @param string $title 名称
* @param string $url 链接
*/
public function add_crumb($title, $url = false) {
$this->breadcrumb[] = array('title' => $title, 'url' => $url);
return true;
}
/**
* 更改默认分隔符
* @param string $new_link 分割字符
*/
public function change_link($new_link) {
// 将默认的分隔符替换成自定义的
$this->link_type = ' ' . $new_link . ' ';
return true;
}
/**
* 组合完成面包屑输出
* @return string 完整面包屑
*/
public function output() {
$counter = 0;
// 遍历所有面包屑
foreach($this->breadcrumb as $key => $val) {
// 添加分隔符
if($counter > 0) {
$this->output .= $this->link_type;
}
if($val['url']) {
$this->output .= '<a href="' . $val['url'] . '">' . $val['title'] . '</a>';
} else {
$this->output .= $val['title'];
}
$counter++;
}
return $this->output;
}
}
使用方法:
// 加载面包屑类
$this->load->library('breadcrumb');
$this->breadcrumb->add_crumb('首页', site_url());
$this->breadcrumb->add_crumb('一级目录', '/cate/1');
$this->breadcrumb->add_crumb('exampleArticle');
$this->breadcrumb->change_link('->');
$breadcrumb = $this->breadcrumb->output();