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

<?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

<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

发表评论

电子邮件地址不会被公开。 必填项已用*标注