How to store my menu structure
I am creating a web site and I want the menus to be dynamically generated. Factors that can effect the menus are the page's position in the site hierarchy, the access level of the user looking at the page, and the type of page (news post, event details, product page, etc).
Originally I thought of creating a mysql database containing menu items with foreign keys and additional details to each item, (target url of menu item, parent menu item, title of item, etc). But I s开发者_如何学Gotarted running into issues of item ordering, multi layered menus and multiple menus.
Then I thought why use a flat relational database when I can have a xml file that has the structure and order explicitly stated. It rarely will change, the pages will have to query the MySQL database to get their contents, it can include some menu ids.
Can you see any pitfalls of this method? I don't have alot of experience with xml other than using it as a template that I walk to generate other structures. How easy is it to manipulate in php and javascript?
If the menu hierarchy was to be created once and updated extremely rarely, you could store the object as a serialised array/object of your choosing. The advantage here is that serialize()
/deserialize()
is significantly faster than parsing XML. For this you would have to write code to update the serialized object/array, but you would have to do that for XML as well. It would also keep the preference for the code to be XML and reduce portability. Con for this is not too portable outside of PHP, and pro it's really fast
You could apply the json_encode/json_decode instead of serialize if you wanted to keep it a bit more portable. Con for this json_encode is slower than serialization, pro more portable to other languages, like saayyy, Javascript.
In MySQL's defence, you can store/add/remove elements to a hierarchy without the method you described using an adjacency list, keeping things a bit more compact. Con a bit of a mind warp to get your head around it, pro faster if the list gets big and eternally changeable into many different formats.
It will work with XML, for example with SimpleXML. However XML is a bit memory and CPU hungry.
The most comfortable way would be, when you can hold the hole menu structure as a nested array. So maybe you can define your structure in directly in native PHP? You can create one file:
<?php return array(
/* put your nested array structure here */
);
And call this structure in your logic like:
<?php
$structure = include('structure.php');
This technique is not so well known but really lightweight and straight forward!
Otherwise you can use parse_ini_file() or stay with the XML or parse it directly to an array.
When you go back to a database solutions maybe "nested sets" could help you once (if you like complicated but clever stuff ;-) ).
精彩评论