Magento 2.1 Multistore – Create Module for One Store Only

magento-2.1modulemultistore

In a Magento 2 multistore, is there a way to create a module available for one particular store only?

I know that I can disable a module using the admin, but that only disables the output of it. Is it possible to add some kind of rule into module.xml or something like that to limit the scope of the module?

Best Answer

No, there is no rule you can set in module.xml to have a module enabled in one store only but you can do this:
Create an enabled/disabled setting in system.xml in your module.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <section id="your_module_name">
            <group id="settings" translate="label" sortOrder="1000" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>MOdule settings</label>
                <field id="enable" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
                    <label>Enable My module</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
             </group>
         </section>
    </system>
</config>

Then in your class methods (not sure which ones because I don't know how your module works) do this:
First add \Magento\Framework\App\Config\ScopeConfigInterface as a dependency to your class:

protected $scopeConfig;

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

And for your methods that interact with Magento somehow (for example a frontend controller action, or an observer) you can do this:

public function someMethodNameHere($parametersHere)
{
    if (!$this->scopeConfig->isSetFlag('your_module_name/settings/enable', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)) {
         return 'some default value goes here. Can be null, a string, an array, ....';
    }
    //your custom code for the method goes here.
}
Related Topic