Search code examples
phpmagentomagento-1.9

Magento: How to get the root category id for a specific store in an upgrade script?


How do I get the root category in a Magento 1.9 update script?

Find root category of store proposes a solution, but I get an error message after running the script:

Mage registry key "controller" already exists

... as well as a trace:

#0 /var/www/instances/global/app/Mage.php(223): Mage::throwException('Mage registry k...')
#1 /var/www/instances/global/app/code/core/Mage/Core/Model/App.php(762): Mage::register('controller', Object(Mage_Core_Controller_Varien_Front))
#2 /var/www/instances/global/app/code/core/Mage/Core/Model/App.php(1113): Mage_Core_Model_App->_initFrontController()
#3 /var/www/instances/global/app/code/core/Mage/Core/Controller/Varien/Front.php(344): Mage_Core_Model_App->getFrontController()
#4 /var/www/instances/global/app/code/core/Mage/Core/Controller/Varien/Front.php(161): Mage_Core_Controller_Varien_Front->_checkBaseUrl(Object(Mage_Core_Controller_Request_Http))
#5 /var/www/instances/global/app/code/core/Mage/Core/Model/App.php(365): Mage_Core_Controller_Varien_Front->dispatch()
#6 /var/www/instances/global/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#7 /var/www/instances/global/index.php(118): Mage::run('', 'store')
#8 {main}

My script calls the Mage::init first, then tries to read the root category name of the store.

Mage::init();
Mage::app()->getStore(3)->getRootCategoryId();

The error message seems to be quite common; Mage registry key "controller" already exists indicates Mage::run might have been run twice.

I therefore assume that Mage::init also should not be called twice, and is maybe invoked again after my update script is invoked - and this could cause my error message. All assumptions.

What could i do? Omit Mage::init()? But then, I do not get the root id. Destroy the object(s) created by Mage::init()? How?


Solution

  • This code is not elegant, but does not need a Mage::init() call and can therefore invoked in a Magento upgrade script:

    $myStoreId = 4;
    $myStoresRootCategoryId = null;
    foreach (Mage::app()->getStores() as $store) {
        $storeId = $store->getId();
        $rootCategoryId = $store->getGroup()->getRootCategoryId();
        if ($storeId == $myStoreId) {
            $myStoresRootCategoryId = $rootCategoryId;
        }
    }