Created
February 16, 2016 13:37
-
-
Save useless-stuff/c9e3c234861ba6c99249 to your computer and use it in GitHub Desktop.
PHP - CachingIterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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