Build your Menu from a Xml File instead of hard coded in your layout/main.php.
Requirements ¶
Yii 1.1 or above
Installation ¶
Move XmlMenu.php File in your applications components folder (default: protected/components).
Usage ¶
[layout/main.php]
$container = new XmlMenu('menu.xml');
$this->widget(
'zii.widgets.CMenu', array(
'items'=>$container->getData()
));
[menu.xml]
<?xml version="1.0" encoding="utf-8" ?>
<items>
<item>
<label>login</label>
<url>array('site/login');</url>
<visible>Yii::app()->user->isGuest;</visible>
</item>
<item>
<label>Contact</label>
<url>array('site/contact');</url>
</item>
<item>
<label>Logout</label>
<url>array('site/logout');</url>
<visible>!Yii::app()->user->isGuest;</visible>
</item>
</items>
Hints ¶
/protected/config is a good place for storing XmlMenu files.
$container new XmlMenu(Yii::app()->basePath.'/config/menu.xml');
Multi Level Navigation ¶
It's even possible to create multiple Levels of Navigation. Just insert another 'items' in the 'item'. :)
[multimenu.xml]
<?xml version="1.0" encoding="utf-8" ?>
<items>
<item>
<label>top</label>
<url>array('site/login');</url>
<visible>Yii::app()->user->isGuest;</visible>
<items>
<item>
<label>sub1</label>
....
</item>
<item>
<label>sub2</label>
.......
</item>
</items>
</item>
<item>
<label>Contact</label>
<url>array('site/contact');</url>
</item>
<item>
<label>Logout</label>
<url>array('site/logout');</url>
<visible>!Yii::app()->user->isGuest;</visible>
</item>
</items>
What is the reason for this extenison
Either I'm missing something or this extension is a little bit useless...
What is the difference between default menu "hardcoded using PHP associative array" and yours menu "hardcoded using XML"? Yes, your menu is also hardcoded. All you've achieved is to move menu structure to an external file and write it in XML, not as an array (which is faster).
With 30 seconds of so, work, I can also extract menu structure in default, auto-generated Yii aplication, take it away of main layout file and store it in external file, using arrays.
Menu not being hardcoded means, that is dynamic. That can be modified in runtime or is stored in some easily to modify media (like database), not hardcoded into any kind of file using any kind of language.
Reason
I can see the value in this if you create a UI to build the XML, and there are several php xml tree building UI/utilities out there that could be leveraged into a first rate menu building module or extension.
Nice work.
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.