When I think I got my head wrapped around the DI system from Magento 2 something comes up and un-wraps it.
I see in the core code different ways to access a helper.
For example in Magento\Catalog\Controller\Category::_initCategory
there is this:
if (!$this->_objectManager->get('Magento\Catalog\Helper\Category')->canShow($category)) {
return false;
}
But in Magento\Catalog\Block\Category\View
the helper is injected int he constructor
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\Layer\Category $catalogLayer,
\Magento\Framework\Registry $registry,
\Magento\Catalog\Helper\Category $categoryHelper,
array $data = array()
) {
$this->_categoryHelper = $categoryHelper;
$this->_catalogLayer = $catalogLayer;
$this->_coreRegistry = $registry;
parent::__construct($context, $data);
}
This lead me to think that the helpers should be accessed differently in controllers and blocks (and models) but then I found a controller where a helper is injected in the constructor Magento\Catalog\Controller\Adminhtml\Product\Action\Attribute
.
Please clear the fog for me.
When should I use DI and when should I use objectManager
? and why?
I've read this question: Instantiating Helpers in Magento 2. This is just a follow up question on that.