{ Hello Magento 2 }

解决 Magento 2 应用问题,更注重深度挖掘。(ง •̀_•́)ง

0%

magento 2 helper

Helpers are classes that can be used anywhere we want,we can use them in controllers,views,modeles and even in other helpers. Helpers are usually created to provide methods for a common functionality. 它一般位于 <module_dir>/Helper目录下,常用的文件名是 Data.php 它继承自 Magento\Framework\App\Helper\AbstractHelper 因为他的父类已经注入了\Magento\Framework\App\Config\ScopeConfigInterface 所以我们可以在 helper 中使用 $this->scopeConfig->getValue() 来获得配置值。 在 block 中我们可以通过 $this->helper('{Vendor}\{Module}\Helper\Data'); 来获得 helper 。注意,此处一定是右斜杠。path 是左斜杠。 举例: File: ThankIT/HelloWorld/Helper/Data.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
namespace ThankIT\HelloWorld\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\ScopeInterface;

class Data extends AbstractHelper
{

const XML_PATH_HELLOWORLD = 'helloworld/general/';

public function __construct(Context $context)
{
parent::__construct($context);
}

public function getConfigValue($field, $storeId = null)
{
return $this->scopeConfig->getValue(
$field, ScopeInterface::SCOPE_STORE, $storeId
);
}

public function getGeneralConfig($code, $storeId = null)
{
return $this->getConfigValue(self::XML_PATH_HELLOWORLD . $code, $storeId);
}

}

File: app\code\ThankIT\HelloWorld\view\frontend\templates\index\index.phtml

1
2
3
4
5
6
7
<hr>
<h3>get configuration value by helper file</h3>
<?php
$helper = $this->helper('ThankIT\HelloWorld\Helper\Data');
echo $helper->getConfigValue('helloworld/general/display_text');
echo '<br/>';
echo $helper->getGeneralConfig('display_text');

参考 System.xml Configuration