Categories


Archives


Recent Posts


Categories


Magento 2 Object Manager: Not just for Module Classes

astorm

Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Updated for Magento 2! No Frills Magento Layout is the only Magento front end book you'll ever need. Get your copy today!

In Magento 1 there were three “types” of classes which you could instantiate via Magento’s various object factories: Models, Blocks, and Helpers

Mage::getModel('group/class');
Mage::helper('group/class');    
Mage::getSingleton('core/layout')->createBlock('group/class');

In Magento 2, all classes are available to the object manager. **This includes classes in lib*. Consider the Dir object we mentioned in the last post.

$object_manager = MagentoCoreModelObjectManager::getInstance();
$dir = $object_manager->get('MagentoAppDir'); 

This object comes from a file in Magento’s lib folder.

lib/Magento/App/Dir.php

In Magento 1 library classes were directly instantiated via PHP. The above would have looked something like this

$dir = new Magento_App_Dir;

The consequences of this? We should be able to rewrite classes in the lib folder without relying on a code-pool override. Which is good, because there are no code-pool overrides in Magento 2.

Copyright © Alana Storm 1975 – 2023 All Rights Reserved

Originally Posted: 10th November 2013

email hidden; JavaScript is required