1

Is it possible to use PHP class constants as values in the config.xml file?

For example, if we have this config.xml file:

<?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>
        <custommodule>
            <settings>
                <is_active>1</is_active>
                <mode>MODE</mode>
                <send_notification_email>0</send_notification_email>
            </settings>
        </custommodule>
    </default>
</config>

I would like to use a PHP class constant to output the value for the "mode". Is there a way to achieve this?

2 Answers 2

0

You can use a backend_model in your config.xml node:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <your>
            <path>
                <field backend_model="Vendor\Module\Model\Config"/>
            </path>
        </your>
    </default>
</config>

Then, in \Vendor\Module\Model\Config:

class \Vendor\Module\Model\Config implements \Magento\Framework\App\Config\Data\ProcessorInterface
{
    const MY_CONST = 'My constant value';

    public function processValue($value)
    {
        return self::MY_CONST;
    }
}

From there, any additional complex logic can be added.

-1

This should be possible using PHPs constant method.

Something like this:

$configValue = $this->scopeConfig->getValue(
   'custommodule/settings/mode',
   ScopeInterface::SCOPE_STORE
);

$constantValue = constant($configValue);
2
  • I think the OP is asking how to use an existing class constant as the value in the XML. Ie something like <mode>Vendor\MyModule\Model\MyModel::MODE_VALUE</mode>, which for the record, doesn't work.
    – Dom
    Oct 31, 2020 at 10:56
  • I am not sure about the config.xml file but class constants can be used in di.xml argument replacement using xsi:type="const" for <argument ... />. It can also be used in <item ... /> tags
    – Ejaz
    Jun 20, 2021 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.