Skip to content

Instantly share code, notes, and snippets.

@useless-stuff
Created February 16, 2016 13:37
Show Gist options
  • Select an option

  • Save useless-stuff/c9e3c234861ba6c99249 to your computer and use it in GitHub Desktop.

Select an option

Save useless-stuff/c9e3c234861ba6c99249 to your computer and use it in GitHub Desktop.
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment