PHP - CachingIterator
<?php
$nav = array(
'Home' => '/home',
'Products' => '/products',
'Company' => '/company',
'Privacy Policy' => '/privacy-policy',
);
/**
* Class NavBuilder
*/
class NavBuilder extends CachingIterator
{
/**
* Override the current() method to modify the return value
* for the given index.
*
* @access public
* @return string
*/
public function current()
{
// get the name and url of the nav item
$name = parent::key();
$url = parent::current();
// determine if we're on the last element
// cacheIterator
if ($this->hasNext()) {
return '<li><a href="'.$url.'">'.$name.'</a></li>';
} else {
return '<li class="last"><a href="'.$url.'">'.$name.'</a></li>';
}
}
/**
* Outputs the navigation.
*/
public function render()
{
$output = '<ul>';
foreach ($this as $iterator) {
$output .= $this->current();
}
$output .= '</ul>';
return $output;
}
}
try {
$navBar = new NavBuilder(new ArrayIterator($nav));
echo $navBar->render();
} catch (Exception $e) {
var_dump($e);
}