course/lib: Cache get_categories() using a static variable (MDL-11938)

Some recursive functions call get_categories() repeatedly to get all of the
child categories of the current one.

This commit create a lazily-initialized cache of all of the categories so
that the database is only queried once to retrieve all of the categories.

It speeds up the both the homepage and the course edit page (where the
categories are displayed in combo boxes).
This commit is contained in:
fmarier 2007-12-17 04:49:27 +00:00
parent 2efa773446
commit 9bb19e5827

View File

@ -1580,6 +1580,32 @@ function rebuild_course_cache($courseid=0) {
}
function get_child_categories($parent) {
/// Returns an array of the children categories for the given category
/// ID by caching all of the categories in a static hash
static $allcategories = null;
// only fill in this variable the first time
if (null == $allcategories) {
$allcategories = array();
$categories = get_categories();
foreach ($categories as $category) {
if (empty($allcategories[$category->parent])) {
$allcategories[$category->parent] = array();
}
$allcategories[$category->parent][] = $category;
}
}
if (empty($allcategories[$parent])) {
return array();
} else {
return $allcategories[$parent];
}
}
function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
/// Given an empty array, this function recursively travels the
@ -1605,7 +1631,7 @@ function make_categories_list(&$list, &$parents, $category=NULL, $path="") {
$category->id = 0;
}
if ($categories = get_categories($category->id)) { // Print all the children recursively
if ($categories = get_child_categories($category->id)) { // Print all the children recursively
foreach ($categories as $cat) {
if (!empty($category->id)) {
if (isset($parents[$category->id])) {
@ -1643,7 +1669,7 @@ function print_whole_category_list($category=NULL, $displaylist=NULL, $parentsli
$category->id = "0";
}
if ($categories = get_categories($category->id)) { // Print all the children recursively
if ($categories = get_child_categories($category->id)) { // Print all the children recursively
$countcats = count($categories);
$count = 0;
$first = true;
@ -1782,7 +1808,7 @@ function print_courses($category) {
global $CFG;
if (!is_object($category) && $category==0) {
$categories = get_categories(0); // Parent = 0 ie top-level categories only
$categories = get_child_categories(0); // Parent = 0 ie top-level categories only
if (is_array($categories) && count($categories) == 1) {
$category = array_shift($categories);
$courses = get_courses_wmanagers($category->id,