Magento2 ObjectManager preferences

When developing with Magento2 you have maybe come to the question were is my logger for example. This was the way in Magento before.

Mage::log('Some log message', null, 'file.log');

Maybe you have already found the logger here for example in the class Magento\Backup\Controller\Adminhtml\Index\Rollback.

$this->_objectManager->get('Psr\Log\LoggerInterface')->info($e->getMessage());

Today I don't want to show you the logger. More interesting for me are the shared instances inside of the Objectmanager that you can use with the fucntion get.

The general object manager can be found in this class Magento\Framework\ObjectManager\ObjectManager and it implements the interface \Magento\Framework\ObjectManagerInterface. Here you see the get function.

/**
 * Retrieve cached object instance
 *
 * @param string $type
 * @return mixed
 */
public function get($type)
{
    $type = ltrim($type, '\\');
    $type = $this->_config->getPreference($type);
    if (!isset($this->_sharedInstances[$type])) {
        $this->_sharedInstances[$type] = $this->_factory->create($type);
    }
    return $this->_sharedInstances[$type];
}

Adding a shared instance

You can add your own shared instance with the preference tag in your etc/di.xml. For example here a snipped of magento/module-backend/etc/di.xml.

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <!-- ... -->
    <preference for="Magento\Framework\App\Config\Storage\WriterInterface" type="Magento\Framework\App\Config\Storage\Writer" />
    <!-- ... -->
</config>

A list of shared instances

Here is a default list of shared instances that you can use with the get function.

typeinstance
Psr\Log\LoggerInterfaceMagento\Framework\Logger\Monolog
Magento\Framework\View\Template\Html\MinifierInterfaceMagento\Framework\View\Template\Html\Minifier
Magento\Framework\ObjectManager\FactoryInterfaceMagento\Framework\ObjectManager\Factory\Dynamic\Developer
Magento\Framework\Search\Adapter\Mysql\Filter\PreprocessorInterfaceMagento\Framework\Search\Adapter\Mysql\Filter\Preprocessor
Magento\Framework\Search\Adapter\Mysql\Field\ResolverInterfaceMagento\Framework\Search\Adapter\Mysql\Field\Resolver
Magento\Framework\Search\Request\Aggregation\StatusInterfaceMagento\Framework\Search\Request\Aggregation\Status
Magento\Framework\Search\Adapter\Mysql\Field\FieldInterfaceMagento\Framework\Search\Adapter\Mysql\Field\Field
Magento\Framework\App\RequestInterfaceMagento\Framework\App\Request\Http
Magento\Framework\App\Request\PathInfoProcessorInterfaceMagento\Store\App\Request\PathInfoProcessor
Magento\Framework\App\ResponseInterfaceMagento\Framework\App\Response\Http
Magento\Framework\App\RouterListInterfaceMagento\Framework\App\RouterList
Magento\Framework\App\FrontControllerInterfaceMagento\Framework\App\FrontController
Magento\Framework\App\CacheInterfaceMagento\Framework\App\Cache\Proxy
Magento\Framework\App\Cache\StateInterfaceMagento\Framework\App\Cache\State
Magento\Framework\App\Cache\TypeListInterfaceMagento\Framework\App\Cache\TypeList
Magento\Store\Model\StoreManagerInterfaceMagento\Store\Model\StoreManager
Magento\Framework\View\DesignInterfaceMagento\Theme\Model\View\Design\Proxy
Magento\Framework\View\Design\ThemeInterfaceMagento\Theme\Model\Theme
Magento\Framework\View\Design\Theme\ResolverInterfaceMagento\Theme\Model\Theme\Resolver
Magento\Framework\View\ConfigInterfaceMagento\Framework\View\Config
Magento\Framework\View\Asset\Bundle\ConfigInterfaceMagento\Framework\View\Asset\Bundle\Config
Magento\Framework\Locale\ListsInterfaceMagento\Framework\Locale\TranslatedLists
Magento\Framework\Api\AttributeTypeResolverInterfaceMagento\Framework\Reflection\AttributeTypeResolver
Magento\Framework\Api\Search\SearchResultInterfaceMagento\Framework\Api\Search\SearchResult
Magento\Framework\Api\Search\SearchCriteriaInterfaceMagento\Framework\Api\Search\SearchCriteria
Magento\Framework\Api\Search\DocumentInterfaceMagento\Framework\Api\Search\Document
Magento\Framework\Api\Search\AggregationInterfaceMagento\Framework\Search\Response\Aggregation
Magento\Framework\Api\ExtensionAttribute\JoinDataInterfaceMagento\Framework\Api\ExtensionAttribute\JoinData
Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterfaceMagento\Framework\Api\ExtensionAttribute\JoinProcessor
Magento\Framework\Locale\ConfigInterfaceMagento\Framework\Locale\Config
Magento\Framework\Notification\NotifierInterfaceMagento\Framework\Notification\NotifierPool
Magento\Framework\UrlInterfaceMagento\Framework\Url
Magento\Framework\Url\EncoderInterfaceMagento\Framework\Url\Encoder
Magento\Framework\Url\DecoderInterfaceMagento\Framework\Url\Decoder
Magento\Framework\Data\Collection\Db\FetchStrategyInterfaceMagento\Framework\Data\Collection\Db\FetchStrategy\Query
Magento\Framework\Config\ScopeInterfaceMagento\Framework\Config\Scope
Magento\Framework\Config\FileResolverInterfaceMagento\Framework\App\Config\FileResolver
Magento\Framework\Config\CacheInterfaceMagento\Framework\App\Cache\Type\Config
Magento\Framework\Config\ValidationStateInterfaceMagento\Framework\App\Arguments\ValidationState
Magento\Framework\Module\ModuleListInterfaceMagento\Framework\Module\ModuleList
Magento\Framework\Component\ComponentRegistrarInterfaceMagento\Framework\Component\ComponentRegistrar
Magento\Framework\Event\ConfigInterfaceMagento\Framework\Event\Config
Magento\Framework\Event\InvokerInterfaceMagento\Framework\Event\Invoker\InvokerDefault
Magento\Framework\Interception\PluginListInterfaceMagento\Framework\Interception\PluginList\PluginList
Magento\Framework\Event\ManagerInterfaceMagento\Framework\Event\Manager\Proxy
Magento\Framework\View\LayoutInterfaceMagento\Framework\View\Layout
Magento\Framework\View\Layout\ProcessorInterfaceMagento\Framework\View\Model\Layout\Merge
Magento\Framework\View\Url\ConfigInterfaceMagento\Framework\View\Url\Config
Magento\Framework\App\Route\ConfigInterfaceMagento\Framework\App\Route\Config
Magento\Framework\App\ResourceConnection\ConfigInterfaceMagento\Framework\App\ResourceConnection\Config\Proxy
Magento\Framework\Oauth\OauthInterfaceMagento\Framework\Oauth\Oauth
Magento\Framework\View\Design\Theme\Domain\PhysicalInterfaceMagento\Theme\Model\Theme\Domain\Physical
Magento\Framework\View\Design\Theme\Domain\VirtualInterfaceMagento\Theme\Model\Theme\Domain\Virtual
Magento\Framework\View\Design\Theme\Domain\StagingInterfaceMagento\Theme\Model\Theme\Domain\Staging
Magento\Framework\Json\EncoderInterfaceMagento\Framework\Json\Encoder
Magento\Framework\Json\DecoderInterfaceMagento\Framework\Json\Decoder
Magento\Framework\Message\ManagerInterfaceMagento\Framework\Message\Manager
Magento\Framework\App\Config\ValueInterfaceMagento\Framework\App\Config\Value
Magento\Framework\Interception\ChainInterfaceMagento\Framework\Interception\Chain\Chain
Magento\Framework\Module\Output\ConfigInterfaceMagento\Framework\Module\Output\Config
Magento\Framework\View\Design\Theme\CustomizationInterfaceMagento\Framework\View\Design\Theme\Customization
Magento\Framework\View\Asset\ConfigInterfaceMagento\Framework\View\Asset\Config
Magento\Framework\Image\Adapter\ConfigInterfaceMagento\Framework\Image\Adapter\Config
Magento\Framework\View\Design\Theme\Image\PathInterfaceMagento\Theme\Model\Theme\Image\Path
Magento\Framework\Session\Config\ConfigInterfaceMagento\Framework\Session\Config
Magento\Framework\Session\SidResolverInterfaceMagento\Framework\Session\SidResolver\Proxy
Magento\Framework\Stdlib\Cookie\CookieScopeInterfaceMagento\Framework\Stdlib\Cookie\CookieScope
Magento\Framework\Stdlib\Cookie\CookieReaderInterfaceMagento\Framework\Stdlib\Cookie\PhpCookieReader
Magento\Framework\Stdlib\CookieManagerInterfaceMagento\Framework\Stdlib\Cookie\PhpCookieManager
Magento\Framework\TranslateInterfaceMagento\Framework\Translate
Magento\Framework\Config\ScopeListInterfaceinterceptionConfigScope
Magento\Framework\View\Design\Theme\Label\ListInterfaceMagento\Theme\Model\ResourceModel\Theme\Collection
Magento\Framework\Mview\ConfigInterfaceMagento\Framework\Mview\Config
Magento\Framework\Mview\ViewInterfaceMagento\Framework\Mview\View
Magento\Framework\Mview\ProcessorInterfaceMagento\Framework\Mview\Processor
Magento\Framework\Mview\View\CollectionInterfaceMagento\Framework\Mview\View\Collection
Magento\Framework\Mview\View\SubscriptionInterfaceMagento\Framework\Mview\View\Subscription
Magento\Framework\Mview\View\ChangelogInterfaceMagento\Framework\Mview\View\Changelog
Magento\Framework\Api\MetadataServiceInterfaceMagento\Framework\Api\DefaultMetadataService
Magento\Framework\Api\MetadataObjectInterfaceMagento\Framework\Api\AttributeMetadata
Magento\Framework\Api\SearchCriteriaInterfaceMagento\Framework\Api\SearchCriteria
Magento\Framework\App\Rss\UrlBuilderInterfaceMagento\Framework\App\Rss\UrlBuilder
Magento\Framework\DB\LoggerInterfaceMagento\Framework\DB\Logger\Quiet
Magento\Framework\App\ResourceConnection\ConnectionAdapterInterfaceMagento\Framework\Model\ResourceModel\Type\Db\Pdo\Mysql
Magento\Framework\DB\QueryInterfaceMagento\Framework\DB\Query
Magento\Framework\App\ProductMetadataInterfaceMagento\Framework\App\ProductMetadata
Magento\Framework\Acl\CacheInterfaceMagento\Framework\Acl\Cache
Magento\Framework\App\AreaInterfaceMagento\Framework\App\Area
Magento\Framework\Setup\ModuleDataSetupInterfaceMagento\Setup\Module\DataSetup
Magento\Framework\AuthorizationInterfaceMagento\Framework\Authorization
Magento\Framework\Authorization\PolicyInterfaceMagento\Framework\Authorization\Policy\DefaultPolicy
Magento\Framework\Authorization\RoleLocatorInterfaceMagento\Framework\Authorization\RoleLocator\DefaultRoleLocator
Magento\Framework\Session\SessionManagerInterfaceMagento\Framework\Session\Generic
Magento\Framework\App\Config\ScopeConfigInterfaceMagento\Framework\App\Config
Magento\Framework\App\Config\ReinitableConfigInterfaceMagento\Framework\App\ReinitableConfig
Magento\Framework\App\Config\MutableScopeConfigInterfaceMagento\Framework\App\MutableScopeConfig
Magento\Framework\App\Config\Storage\WriterInterfaceMagento\Framework\App\Config\Storage\Writer
Magento\Framework\Config\ConverterInterfaceMagento\Framework\Config\Converter\Dom
Magento\Framework\App\DefaultPathInterfaceMagento\Framework\App\DefaultPath\DefaultPath
Magento\Framework\Encryption\EncryptorInterfaceMagento\Framework\Encryption\Encryptor
Magento\Framework\Filter\Encrypt\AdapterInterfaceMagento\Framework\Filter\Encrypt\Basic
Magento\Framework\Cache\ConfigInterfaceMagento\Framework\Cache\Config
Magento\Framework\View\Asset\MergeStrategyInterfaceMagento\Framework\View\Asset\MergeStrategy\Direct
Magento\Framework\App\ViewInterfaceMagento\Framework\App\View
Magento\Framework\Data\Collection\EntityFactoryInterfaceMagento\Framework\Data\Collection\EntityFactory
Magento\Framework\Translate\InlineInterfaceMagento\Framework\Translate\Inline
Magento\Framework\Session\ValidatorInterfaceMagento\Framework\Session\Validator
Magento\Framework\Session\StorageInterfaceMagento\Framework\Session\Storage
Magento\Framework\Url\RouteParamsResolverInterfaceMagento\Framework\Url\RouteParamsResolver
Magento\Framework\Url\QueryParamsResolverInterfaceMagento\Framework\Url\QueryParamsResolver
Magento\Framework\Url\ScopeResolverInterfaceMagento\Framework\Url\ScopeResolver
Magento\Framework\Url\SecurityInfoInterfaceMagento\Framework\Url\SecurityInfo\Proxy
Magento\Framework\Locale\CurrencyInterfaceMagento\Framework\Locale\Currency
Magento\Framework\CurrencyInterfaceMagento\Framework\Currency
Magento\Framework\Locale\FormatInterfaceMagento\Framework\Locale\Format
Magento\Framework\Locale\ResolverInterfaceMagento\Framework\Locale\Resolver
Magento\Framework\Stdlib\DateTime\TimezoneInterfaceMagento\Framework\Stdlib\DateTime\Timezone
Magento\Framework\Module\ResourceInterfaceMagento\Framework\Module\ModuleResource
Magento\Framework\Pricing\Amount\AmountInterfaceMagento\Framework\Pricing\Amount\Base
Magento\Framework\Api\SearchResultsInterfaceMagento\Framework\Api\SearchResults
Magento\Framework\Api\AttributeInterfaceMagento\Framework\Api\AttributeValue
Magento\Framework\Model\ResourceModel\Db\TransactionManagerInterfaceMagento\Framework\Model\ResourceModel\Db\TransactionManager
Magento\Framework\Api\Data\ImageContentInterfaceMagento\Framework\Api\ImageContent
Magento\Framework\Api\ImageContentValidatorInterfaceMagento\Framework\Api\ImageContentValidator
Magento\Framework\Api\ImageProcessorInterfaceMagento\Framework\Api\ImageProcessor
Magento\Framework\Code\Reader\ClassReaderInterfaceMagento\Framework\Code\Reader\ClassReader
Magento\Framework\Stdlib\DateTime\DateTimeFormatterInterfaceMagento\Framework\Stdlib\DateTime\DateTimeFormatter
Magento\Framework\Api\Search\SearchInterfaceMagento\Framework\Search\Search
Magento\Framework\View\Design\FileResolution\Fallback\ResolverInterfaceMagento\Framework\View\Design\FileResolution\Fallback\Resolver\Simple
Magento\Framework\Session\SaveHandlerInterfaceMagento\Framework\Session\SaveHandler
Next Previous