Skip to main content

Where to use object manager in Magento 2

You can depend on and use the ObjectManager class in the following scenarios:
  • You can use the object manager in static magic methods like __wakeup(), __sleep(), etc.
  • An example can be found in the __wakeup() method in the Magento/Eav/Model/Entity/Attribute/AbstractAttribute class.
  • You can use the ObjectManager to maintain backward compatibility for a constructor.
  • In a global scope, like in fixtures of integration tests, you can use the object manager.
  • The object manager can be a dependency in classes used for the creation of objects, e.g. factories or proxies.
In nutshell al dependencies(except above cases) must be injected in the constructor. Dependency Injection will do the work. Then you will do specialised methods that return what you need.
More specifically in the scenario of providing data to templates, Magento recommends using ViewModels which are nothing but service classes that provide needed information in templates. These view models should be set in the layout files. see docblock of Magento\View\Framework\Element\Template

 * Standard Magento block.
 * Should be used when you declare a block in frontend area layout handle.
 *
 * Avoid extending this class.
 *
 * If you need custom presentation logic in your blocks, use this class as block, and declare
 * custom view models in block arguments in layout handle file.
 *
 * Example:
 * <block name="my.block" class="Magento\Backend\Block\Template" template="My_Module::template.phtml" >
 *      <arguments>
 *          <argument name="viewModel" xsi:type="object">My\Module\ViewModel\Custom</argument>
 *      </arguments>
 * </block>
Such a ViewModel class is Magento\Catalog\ViewModel\Breadcrums.
Remember all classes that are passed through layout files must implement the Magento\Framework\View\Element\Block\ArgumentInterface
More on Dependency Injection in Magento can be found here
A good official reference of Magento coding standards can be found here

Comments

Popular posts from this blog

Magento 2 product collection Filtering multi-select attribute values

  If you have multi-select attribute of product like below If you want filter value for this option Use below syntax to get product data: ->addAttributeToFilter('store_model', array('finset' => $params['store_model'])) finset key is used for multiselect attribute filter. $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $products = $objectManager->get('Magento\Catalog\Model\Product')         ->getCollection()         ->addAttributeToSelect('*')         ->addAttributeToSelect('store_brand')         ->addAttributeToSelect('store_model')         ->addAttributeToSelect('store_year')         ->addAttributeToFilter('store_brand', array('finset' => $params['store_brand']))         ->addAttributeToFilter('store_model', array('finset' => $params['store_model']))         ->ad...

magento 2 best seller product display based on current category and subcategories

Magento 2 getting best seller based on category wise displaying i have done below for that to implement this functionality it is working fine for me. step 1 create block file in our module folder <?php namespace Pawan\Bestseller\Block; use Magento\Catalog\Api\CategoryRepositoryInterface; class Bestsellercategory extends \Magento\Catalog\Block\Product\ListProduct {     /**      * Product collection model      *      * @var Magento\Catalog\Model\Resource\Product\Collection      */     protected $_collection;     /**      * Product collection model      *      * @var Magento\Catalog\Model\Resource\Product\Collection      */     protected $_productCollection;     /**      * Image helper      *      * @var Magento\Catalog\Helper\Image     ...

Integrity constraint violation: 1052 Column 'created_at' in where clause is ambiguous

When trying to filter sales order grid with From and To dates it was redirecting to dashboard.after that again i tried to open sales order grind it is generating reports in reports file it showing. "Integrity constraint violation: 1052 Column 'created_at' in where clause is ambiguous" means it is finding a another created_at field. because when we adding or joining the other table then it has also a field named as created_at. So below is the  solution for this error. magento that created_at is of the main_table not of my custom table. Find the below code in the sales order grid.php file. $this->addColumn('created_at', array(            'header' => Mage::helper('sales')->__('Purchased On'),             'index' => 'created_at',             'type' => 'datetime',             'width' => '100px',         )); ...