سؤال

The latest builds of Magento 2 have done away with the Mage class. This mean we've lost the Mage::helper method.

Is there a replacement technique (helper factory?) for instantiating helpers in Magento 2? Or are we expected to use the new Object manager class, and just instantiate the helper as a singleton/cached object with get (vs. create)

هل كانت مفيدة؟

المحلول

I see you came to right solution, just want to summarize.

Constructor injection should be used to retrieve helper (or any other instance) in whatever class you need:

class SomeClass
{
    public function __construct(\Magento\Core\Helper\Data $helper)
    {
        $this->helper = $helper;
    }

    public function doSmth()
    {
        $this->helper->someMethod();
    }
}

Notice that no phpDoc comments are required, Magento will read constructor signature directly to figure out what dependencies are required.

\Magento\Core\Helper\Factory should be used only in those rare cases when you have to call a lot of multiple helpers, or you don't know exactly which one you need.

Usage of Object Manager directly is strictly discouraged. So please avoid using:

\Magento\Core\Model\ObjectManager::getInstance()

It's there only for serialization/deserialization.

نصائح أخرى

It looks like Magento's encouraging folks to use their new automatic dependency injection system to get helpers and models into objects via the object's constructor.

The short version? If you have an object that's instantiated by the object manager, and decorate a constructor with a PHPDoc @param, and the parameters has a proper type hint set, the object manager will automatically instantiate the helper (or, I believe, other objects) for you.

For example, the following constructor would inject a a core data helper into the object.

/**
* @param \Magento\Core\Helper\Data $coreData
*/        
public function __construct(\Magento\Core\Helper\Data $coreData)
{
    $this->_coreHelper = $coreData;            
}

Apart from all above answers, if you have to use helper in phtml template you can simply do like this:

$this->helper('[Vendor]\[Module]\Helper\[Helper Name]');

I hope it is helpful if somebody didn't know it before ;)

The way that helpers are instantiated (at least for the new Backend (~dev50) module) are via a helperFactory:

/**
 * Return helper object
 *
 * @param string $name
 * @return \Magento\Core\Helper\AbstractHelper
 */
public function helper($name)
{
    return $this->_helperFactory->get($name);
}

Which is essentially just a specialized type of a model factory. E.g: Magento\Core\Block\Context line 143 (dev50) as part of the constructor:

\Magento\Core\Model\Factory\Helper $helperFactory

The helper factory will return the requested model based on the class name and ensure that it is an instanceof the helper abstract class:

/**
 * 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;
}

If you were to implement this yourself it seems Magento core is loading it in one of two ways:

Roll your own factory:

$objectManager = \Magento\Core\Model\ObjectManager::getInstance();

$helperFactory = $objectManager->get('\Magento\Core\Model\Factory\Helper');
$helper = $helperFactory->get('\PulseStorm\Commercebug\Helper\Data');

Or just grab it directly:

$helper = \Magento\Core\Model\ObjectManager::getInstance()->get('Magento\Core\Helper\Data');

Try this way

$helper = \Magento\Framework\App\ObjectManager::getInstance()->get('Xx\Xx\Helper\Xx');
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى magento.stackexchange
scroll top