如何在我的模块中添加自定义帮助器?


9

如何在Magento 2模块中创建新的Helper或重写/重写Core Helper?

我尝试将依赖项添加到module.xml“自定义模块”中,但它根本不会加载Helper类。

下面是我的module.xml;

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
  <module name="Company1_Module1" schema_version="1.0.0" setup_version="1.0.0">
        <sequence>Magento_Directory</sequence>
  </module>
</config>

Answers:


20

创建: app/code/Company1/Module1/composer.json

{
    “ name”:“ company1 / module-module1”,
    “ description”:“”,
    “要求”:{
        “ php”:“〜5.5.0 |〜5.6.0 |〜7.0.0”,
        “ magento /框架”:“ 100.0。*”,
        “ magento / module-ui”:“ 100.0。*”,
        “ magento / module-config”:“ 100.0。*”,
        “ magento /模块目录”:“ 100.0。*”
    },
    “ type”:“ magento2-module”,
    “ version”:“ 100.0.0”,
    “执照”: [
        “ OSL-3.0”,
        “ AFL-3.0”
    ],
    “自动加载”:{
        “文件”:[“ registration.php”],
        “ psr-4”:{
            “ Company1 \\ Module1 \\”:“”
        }
    }
}

创建: app/code/Company1/Module1/registration.php

\ Magento \ Framework \ Component \ ComponentRegistrar :: register(
    \ Magento \ Framework \ Component \ ComponentRegistrar :: MODULE,
    'Company1_Module1',
    __DIR__
);

创建: app/code/Company1/Module1/etc/module.xml

<?xml version =“ 1.0”?>
<config xmlns:xsi =“ http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation =“ urn:magento:framework:Module / etc / module.xsd”>
    <module name =“ Company1_Module1” setup_version =“ 2.0.0”>
        <序列>
            <module name =“ Magento_Directory” />
        </ sequence>
    </ module>
</ config>

模块创建完成。因此,现在在Helper文件夹中创建helper类。

app/code/Company1/Module1/Helper/Data.php

名称空间Company1 \ Module1 \ Helper;

类数据扩展\ Magento \ Framework \ App \ Helper \ AbstractHelper
{
    公共函数someMethod()
    {
        返回1;
    }
}

如何在控制器中使用助手类

$this->_objectManager->create('Company1\Module1\Helper\Data')->someMethod();

如何在块内使用助手类

公共功能__construct(
        \ Magento \ Framework \ View \ Element \ Template \ Context $ context,
        \ Company1 \ Module1 \ Helper \ Data $ helper,
        数组$ data = []
    ){
        $ this-> helper = $ helper;
        parent :: __ construct($ context,$ data);
    }

所以,$this->helper现在是数据的实例。

要覆盖任何类,可以使用preference

app/code/Company1/Module1/etc/di.xml

<xml版本=“ 1.0”?>
<config xmlns:xsi =“ http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation =“ urn:magento:framework:ObjectManager / etc / config.xsd”>
    <preference for =“ Magento \ Directory \ Helper \ Data” type =“ Company1 \ Module1 \ Helper \ Data” />
</ config>

您也可以使用插件。插件是克服重写冲突的最佳方法。有关更多信息,插件示例

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.