Skip to content

Instantly share code, notes, and snippets.

@danielchikaka
Created January 9, 2014 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielchikaka/8332760 to your computer and use it in GitHub Desktop.
Save danielchikaka/8332760 to your computer and use it in GitHub Desktop.
<?php
// include this file in app/start/global.php
View::creator('menu', 'MenuCreator');
View::composer('menu', 'MyMenuComposer');
// you can add as many composers to the same view as you like
View::composer('menu', 'MyOtherMenuComposer');
<?php
// include this file in app/start/global.php
HTML::macro('menuItem', function($item)
{
if (!empty($item['subitems'])) {
return '<li>' . HTML::menu($item['subitems']) . '</li>';
}
if (!empty($item['url'])) {
$url = URL::to($item['url']);
} elseif (!empty($item['route'])) {
$url = URL::route($item['route']);
} elseif (!empty($item['action'])) {
$url = URL::action($item['action']);
}
if (isset($url)) {
return '<li>' . HTML::link($item['title'], $url) . '</li>';
} else {
return '<li>' . HTML::entities($item['title']) . '</li>';
}
});
HTML::macro('menu', function($items)
{
$html = '<ul>';
foreach ($items as $item) {
$html .= HTML::menuItem($item);
}
$html .= '</ul>';
});
<h1>Composed menu</h1>
<?php echo HTML::menu($menu); ?>
<?php
abstract class MenuComposer
{
protected $view;
public final function compose($view)
{
$this->view = $view;
$this->addMenus();
}
protected abstract function addMenus();
protected function add($id, array $items = array())
{
$menu = $this->view->menu;
if (is_array($id)) {
$menu = array_merge($menu, $id);
} elseif (isset($oldMenu[$id])) {
if (isset($oldMenu[$id]['subitems'])) {
$menu[$id] = array_merge($menu[$id], $items);
} elseif (isset($items['subitems'])) {
$menu[$id]['subitems'] = array_merge($menu[$id]['subitems'], $items['subitems']);
} else {
$menu[$id] = $items;
}
} else {
$menu[$id] = $items;
}
$this->view->with('menu', $menu);
}
}
<?php
final class MenuCreator
{
public final function create($view)
{
$view->with('menu', array());
}
}
<?php
class MyMenuComposer extends MenuComposer
{
protected function addMenus()
{
$this->add([
'topmenu1' => [
'title' => 'Top menu 1',
'subitems' => [
['title' => 'Subitem 1', 'url' => 'http://www.example.com' ],
['title' => 'Subitem 2', 'route' => 'my.route.name' ],
]
],
'topmenu2' => [
'title' => 'Top menu 2',
'route' => 'my.route.name',
]
]);
$this->add('topmenu3', [
'title' => 'Top menu 3',
'action' => 'MyController@action',
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment