2013-04-09 78 views
5

我有我的System.Xml模塊,這個開始於:如何獲得magento後端配置xml數據?

<config> 
    <sections> 
     <dev> 
      <groups> 
       <my_module> 
        <label>... 

我想這個標籤的值,從不同的模塊。我該怎麼做?我的第一個想法是,Mage::getConfig('sections/dev/groups/my_module/label'),但這不起作用 - 看起來配置的<sections>區域不可訪問。我也找不出magento加載這個值的位置,它在某個時刻必須做,否則它將無法顯示它。

要完全清楚:我沒有試圖獲取存儲在core_config_data表中的配置數據值,這沒有問題。我希望能夠獲得與其相關的其他屬性 - 例如組標籤或字段的排序順序,並且要做到這一點,我需要能夠讀取配置的<sections>區域。

回答

6

system.xml文件不會與全局配置合併。只有當Magento爲後端管理應用程序的

System -> Configuration 

部分建立用戶界面時,纔會加載它們。除此之外,應用程序對他們沒有用處。

如果你想抓住標籤,你需要自己加載完整的system.xml配置。像這樣的東西應該工作。

//load and merge `system.xml` files 
$config = Mage::getConfig()->loadModulesConfiguration('system.xml');   

//grab entire <sections/> node 
var_dump($config->getNode('sections')->asXml());   

//grab label from a specific option group as a string 
var_dump((string)$config->getNode('sections/dev/groups/restrict/label')); 

正如在這個線程另一個答覆中提到,這裏還有它封裝了一些這個邏輯在getSection方法的adminhtml/config模型類,所以你可以做這樣的事情。

Mage::getSingleton('adminhtml/config')->getSection('dev')->groups->my_module->label 

如果你看看getSection

#File: app/code/core/Mage/Adminhtml/Model/Config.php 
public function getSections($sectionCode=null, $websiteCode=null, $storeCode=null) 
{ 
    if (empty($this->_sections)) { 
     $this->_initSectionsAndTabs(); 
    } 

    return $this->_sections; 
} 

源,並通過後續調用堆棧_initSectionsAndTabs

#File: app/code/core/Mage/Adminhtml/Model/Config.php 
protected function _initSectionsAndTabs() 
{ 
    $config = Mage::getConfig()->loadModulesConfiguration('system.xml') 
     ->applyExtends(); 

    Mage::dispatchEvent('adminhtml_init_system_config', array('config' => $config)); 
    $this->_sections = $config->getNode('sections'); 
    $this->_tabs = $config->getNode('tabs'); 
} 

你會看到這種包裝方法最終調用loadModulesConfiguration方法本身。額外applyExtends如果是old bit of meta-programming in the configuration you can read about here,它是a longer series on configuration loading的一部分。 (自我鏈接,對於StackOverflow答案太長)。

我個人不會用這個搶值從配置的原因是,調度的事件,當你撥打這個電話

Mage::dispatchEvent('adminhtml_init_system_config', array('config' => $config)); 

此事件可能在系統中觸發代碼,假設你將系統配置系統加載到後臺管理控制檯區域。如果你只是想讀取XML樹。只需簡單地加載它並閱讀值似乎是要走的路。當然,您的使用案例可能會有所不同。

+0

剛發佈這個之後發現了一個不同的解決方案......有什麼區別?爲什麼使用loadModulesConfiguration而不是getSingleton('adminhtml/config')更好? – Benubird 2013-04-09 16:22:29

+0

@Benubird用更多的信息和上下文更新了答案。簡短版本:您發現的技術使用'loadModulesConfiguration'方法本身。 – 2013-04-09 16:41:03

2

往往似乎是這種情況,我發現發佈問題後的答案時刻...

這是如何得到部分的/ dev/my_module /標籤:

Mage::getSingleton('adminhtml/config')->getSection('dev')->groups->my_module->label 

正如你所看到的,你需要使用Mage::getSingleton('adminhtml/config')->getSection('dev')獲得後端的配置(您也可以使用->getSections()讓所有的章節迭代)。這將返回一個Mage_Core_Model_Config_Element對象,它是對象樹的根,如圖所示。只要在任何階段執行print_r,就會看到樹的其餘部分,print_r的格式與數組相似,但它不是。