创建: 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>
您也可以使用插件。插件是克服重写冲突的最佳方法。有关更多信息,插件示例