Magento 2のインスタンス化ヘルパー
-
16-10-2019 - |
質問
Magento 2の最新のビルドは Mage
クラス。これは、私たちが失ったことを意味します Mage::helper
方法。
Magento 2にヘルパーをインスタンス化するための交換技術(ヘルパーファクトリー?)はありますか?または、新しいオブジェクトマネージャークラスを使用し、ヘルパーをシングルトン/キャッシュオブジェクトとしてインスタンス化することが期待されていますか? get
(vs。 create
)
解決
私はあなたが正しい解決策に来たのを見ます、ただ要約したいだけです。
コンストラクターインジェクションは、必要なクラスでヘルパー(または他のインスタンス)を取得するために使用する必要があります。
class SomeClass
{
public function __construct(\Magento\Core\Helper\Data $helper)
{
$this->helper = $helper;
}
public function doSmth()
{
$this->helper->someMethod();
}
}
それに注意してください phpdocのコメントは必要ありません, 、Magentoは、コンストラクターの署名を直接読み取り、どの依存関係が必要かを把握します。
Magento Core Helper Factoryは、多くの複数のヘルパーを呼び出す必要がある場合、または必要なものを正確に知らない場合にのみ使用する必要があります。
オブジェクトマネージャーの使用は直接です 厳密に落胆した. 。使用しないでください:
\Magento\Core\Model\ObjectManager::getInstance()
それは、シリアル化/脱介入のためだけにあります。
他のヒント
マゼントの励ましの人々が彼らを使うように 新しい自動依存関係インジェクション オブジェクトのコンストラクターを介してヘルパーとモデルをオブジェクトに入れるシステム。
短いバージョン?オブジェクトマネージャーによってインスタンス化されたオブジェクトがある場合、 と PHPDOCでコンストラクターを飾ります , と パラメーターには適切なタイプのヒントセットがあり、オブジェクトマネージャーは自動的にヘルパー(または他のオブジェクト)をインスタンス化します。 @param
たとえば、次のコンストラクターは、AAコアデータヘルパーをオブジェクトに注入します。
/**
* @param \Magento\Core\Helper\Data $coreData
*/
public function __construct(\Magento\Core\Helper\Data $coreData)
{
$this->_coreHelper = $coreData;
}
上記のすべての回答とは別に、PHTMLテンプレートでヘルパーを使用する必要がある場合は、次のようにできます。
$this->helper('[Vendor]\[Module]\Helper\[Helper Name]');
誰かが以前にそれを知らなかったなら、それが役立つことを願っています;)
ヘルパーがインスタンス化される方法(少なくとも新しいバックエンド(〜DEV50)モジュールの場合)は、ヘルパーファクトリーを介して行われます。
/**
* Return helper object
*
* @param string $name
* @return \Magento\Core\Helper\AbstractHelper
*/
public function helper($name)
{
return $this->_helperFactory->get($name);
}
これは本質的に単なる特殊なタイプのモデル工場です。 EG:Magento Core block Context Line 143(dev50)コンストラクターの一部として:
\Magento\Core\Model\Factory\Helper $helperFactory
ヘルパー工場は、クラス名に基づいて要求されたモデルを返し、それが instanceof
ヘルパー抽象クラス:
/**
* Get helper singleton
*
* @param string $className
* @param array $arguments
* @return \Magento\Core\Helper\AbstractHelper
* @throws \LogicException
*/
public function get($className, array $arguments = array())
{
$className = str_replace('_', '\\', $className);
/* Default helper class for a module */
if (strpos($className, '\Helper\\') === false) {
$className .= '\Helper\Data';
}
$helper = $this->_objectManager->get($className, $arguments);
if (false === ($helper instanceof \Magento\Core\Helper\AbstractHelper)) {
throw new \LogicException(
$className . ' doesn\'t extends Magento\App\Helper'
);
}
return $helper;
}
あなたがこれを自分で実装するなら Magento Coreは2つの方法のいずれかでロードしているようです。
自分の工場を転がす:
$objectManager = \Magento\Core\Model\ObjectManager::getInstance();
$helperFactory = $objectManager->get('\Magento\Core\Model\Factory\Helper');
$helper = $helperFactory->get('\PulseStorm\Commercebug\Helper\Data');
または、直接それをつかむだけです:
$helper = \Magento\Core\Model\ObjectManager::getInstance()->get('Magento\Core\Helper\Data');
このようにしてみてください
$helper = \Magento\Framework\App\ObjectManager::getInstance()->get('Xx\Xx\Helper\Xx');