Magento 1中单次调用多次执行getResourceSingleton()失效问题求助
getResourceSingleton() Calls Hey there, let's break down why your code is misbehaving and fix it right away!
The Root Cause
Magento's getResourceSingleton() method returns a single, reusable instance of the resource model throughout your request lifecycle. When you call load() on it the first time, the category tree data gets loaded into that instance. The second time you call Mage::getResourceSingleton('catalog/category_tree')->load(), you're not getting a fresh object—you're just grabbing the same already-loaded instance. Since the tree is already populated, the second load() call does nothing, which breaks your expected functionality.
The Simple Fix
You only need to fetch the singleton instance once, then reuse it for all your tree operations. Here's your corrected code:
// Fetch the singleton instance ONCE and load it $tree = Mage::getResourceSingleton('catalog/category_tree')->load(); $root = $tree->getNodeById($rootCategoryId); if ($root && $root->getId() == 1) { $root->setName(Mage::helper('catalog')->__('Root')); } $collection = Mage::getModel('catalog/category')->getCollection() ->addAttributeToSelect('name') ->addAttributeToFilter('is_active', '1'); // Continue using $tree for any additional tree operations needed
When You Do Need a Fresh Tree Instance
If you ever need to reload the category tree (for example, after making database changes mid-request), use getResourceModel() instead of getResourceSingleton(). This creates a new instance every time, so load() will pull fresh data each time:
// First fresh tree instance $freshTree1 = Mage::getResourceModel('catalog/category_tree')->load(); // After making changes, get another fresh instance $freshTree2 = Mage::getResourceModel('catalog/category_tree')->load();
A Quick Best Practice
Singleton resources are designed to save system resources by reusing objects. Stick to fetching them once per request whenever possible—it aligns with Magento's architecture and avoids issues like the one you ran into.
内容的提问来源于stack exchange,提问作者SagarPPanchal

