Magento 2-如何读取etc / config.xml中的值?


Answers:


12

您不能直接从中读取值etc/config.xml
我的意思是,您可以,但是直接从那里读取是没有意义的,因为值可能会从stores-> configuration部分覆盖,从而使值不再有用config.xml
相反,您可以从全局合并的配置中读取数据,如果在配置部分中未覆盖该值,则可以从中获取该值config.xml

您可以通过向类添加一个需要读取配置值的依赖项来做到这一点,如下所示:

命名空间Your \ Namespace \ Here;

class YourClassName
{
    protected $scopeConfig;
    public function __construct(
        ....
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        ....
    ) {
        ....
        $this->scopeConfig = $scopeConfig;
        ....
    }
}

然后您可以像这样读取配置值

$path = 'path/to/value';
$value = $this->scopeConfig->getValue($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);

或者,如果它是一个是/否标志,并且您想要获取一个true/false值,则可以这样做:

$flag = $this->scopeConfig->isSetFlag($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);

$path代表由斜线(/)串联的所有标记,直到您的值为止(类似于M1)。

要在其中定义它们,config.xml需要在文件中添加

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default><--! reserved word -->
        <section><!-- anything goes here -->
            <group><!-- anything goes here -->
                <value1>1</value1><!-- anything goes here -->
                <value2>some text</value2><!-- anything goes here -->
            </group>
        </section>
    </default>
</config>

使用上面的代码,

$value = $this->scopeConfig->getValue('section/group/value1', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);  

将返回1

$value = $this->scopeConfig->isSetFlag('section/group/value1', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);  

会回来的true


谢谢。我已经尝试并做了一个例子。github.com/zzpaul/magento2-module-custom-config-demo
Paul
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.