For the past few weeks I’ve been thinking about redesigning my thing/creation system. I spent the majority of Saturday creating a new PHP script to store and categorise my creations. It now stores the creations in a MySQL database instead of serializing PHP data into simple text files using descriptions from $creation.dsc. Using a database allows me to easily categorise the creations by giving them all a category id which relates to entries in the category table. I’m pleased with this application: a few hours of effort and thinking that will last me months of usage.
My introduction page now uses MySQL to retrieve the latest three creations instead of relying on the ‘thing’ page to generate the serialized PHP file. The tables are simple unlike the script that uses them: updating and adding new content involves editing a database row using phpMyAdmin, the script only has to be written once. It is better to create a complicated system that requires little maintenance than a simple system that requires more time to update.
The most complicated feature to implement was subcategories. Creating these included quite a complicated sorting algorithm and a function to find the parent categories. Luckily I only have to make this once because, now I’ve created this category system, I can apply the code to a number of other systems for instance news, forums and software archives.
Sorting categories
This function recursively sorts an array of categories into a hierarchy using raw data rows. At the moment the only improvement to this function I can imagine is using references when passing the lists to reduce script memory usage.
function catSort($rawList, $parentId = 1)
{
$base = array();
$toSort = array();
foreach ($rawList as $id => $item) {
if ($item['parent'] === $parentId && $id !== 1) {
$base[$id] = $item;
} else {
$toSort[$id] = $item;
}
}
foreach ($base as $id => $item) {
$base[$id]['children'] = $this->catSort($toSort, $id);
foreach ($base[$id]['children'] as $child) {
$base[$id]['total'] += $child['total'];
}
}
return $base;
}

Comments