Understanding Context Object and Using Defined Methods from it in Magento 2

Understanding Context Object

As a Magento developer, you must have seen, in most of the Constructors of Magento 2 classes, a $context object is passed. For example:

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Catalog\Model\Design $catalogDesign,
    \Magento\Catalog\Model\Session $catalogSession,
....
    parent::__construct(
        $context,
        $layoutFactory,

To understand it, you should read it as “ActionContext”. It represents the application context in which the action is executed. In simpler words, it gives you access to all objects with application state that a controller action needs, for example the registry or the request object.

The context classes don’t have own functionality, they are just a container for other objects. You can see them as shortcut to not have number of parameters in each controller action. All common parameters are merged in the context object.

Using Defined Methods from Context Object

As we have learned so far, context classes work as a container for other objects, so by using $context object we can access those objects and their associated attributes (methods etc.)

Let’s understand it from an example. If you need to use an object of \Magento\Store\Model\StoreManagerInterface class in your block, by most common practice of DI, you will inject the class in constructor like this:

public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    array $data = []
)
{
    $this->_storeManager = $storeManager;
    parent::__construct($context, $data);
}

This code might work, but still it’s not correct to inject this class as the object of class \Magento\Backend\Block\Template\Context already contains it.

In above case, you will get “Incorrect dependency in class” error while running bin/magento setup:di:compile

This error occurs when we use some class’s object in constructor which is already present in $context object. The correct practice is to use methods directly from the context object rather than injecting it’s class into the constructor like this:

public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    array $data = []
)
{
    $this->_storeManager = $context->getStoreManager();
    parent::__construct($context, $data);
}

Now, let’s see the list of methods in $context object for different classes:

Block Class

$context->getRequest(); // return \Magento\Framework\App\RequestInterface
$context->getUrlBuilder(); // return \Magento\Framework\UrlInterface
$context->getScopeConfig(); // return \Magento\Framework\App\Config\ScopeConfigInterface
$context->getLogger(); // return \Psr\Log\LoggerInterface
$context->getEventManager(); // return \Magento\Framework\Event\ManagerInterface
$context->getStoreManager(); // return \Magento\Store\Model\StoreManagerInterface
$context->getPageConfig(); // return \Magento\Framework\View\Page\Config
$context->getFilesystem(); // return \Magento\Framework\Filesystem
$context->getViewFileSystem(); // return \Magento\Framework\View\FileSystem
$context->getAppState(); // return \Magento\Framework\App\State
$context->getCache(); // return \Magento\Framework\App\CacheInterface
$context->getSession(); // return \Magento\Framework\Session\SessionManagerInterface
$context->getInlineTranslation(); // return \Magento\Framework\Translate\Inline\StateInterface
$context->getEscaper(); // return \Magento\Framework\Escaper
$context->getLocaleDate(); // return \Magento\Framework\Stdlib\DateTime\TimezoneInterface
$context->getDesignPackage(); // return \Magento\Framework\View\DesignInterface
$context->getLayout(); // return \Magento\Framework\View\LayoutInterface
$context->getSidResolver(); // return \Magento\Framework\Session\SidResolverInterface
$context->getAssetRepository(); // return \Magento\Framework\View\Asset\Repository
$context->getViewConfig(); // return \Magento\Framework\View\ConfigInterface
$context->getCacheState(); // return \Magento\Framework\App\Cache\StateInterface
$context->getFilterManager(); // return \Magento\Framework\Filter\FilterManager

Model Class

$context->getLogger(); // return \Psr\Log\LoggerInterface
$context->getCacheManager(); // return \Magento\Framework\App\CacheInterface
$context->getEventDispatcher(); // return \Magento\Framework\Event\ManagerInterface
$context->getAppState(); // return \Magento\Framework\App\State
$context->getLogger(); // return \Psr\Log\LoggerInterface

Helper Class

$context->getRequest(); // return \Magento\Framework\App\RequestInterface
$context->getUrlBuilder(); // return \Magento\Framework\UrlInterface
$context->getScopeConfig(); // return \Magento\Framework\App\Config\ScopeConfigInterface
$context->getLogger(); // return \Psr\Log\LoggerInterface
$context->getEventManager(); // return \Magento\Framework\Event\ManagerInterface
$context->getModuleManager(); // return \Magento\Framework\Module\Manager
$context->getCacheConfig(); // return \Magento\Framework\Cache\ConfigInterface
$context->getHttpHeader(); // return \Magento\Framework\HTTP\Header
$context->getRemoteAddress(); // return \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress
$context->getUrlEncoder(); // return \Magento\Framework\Url\EncoderInterface
$context->getUrlDecoder(); // return \Magento\Framework\Url\DecoderInterface

Controller Class

$context->getActionFlag(); // return \Magento\Framework\App\ActionFlag
$context->getEventManager(); // return \Magento\Framework\Event\ManagerInterface
$context->getObjectManager(); // return \Magento\Framework\ObjectManagerInterface
$context->getRedirect(); // return \Magento\Framework\App\Response\RedirectInterface
$context->getRequest(); // return \Magento\Framework\App\RequestInterface
$context->getResponse(); // return \Magento\Framework\App\ResponseInterface
$context->getUrl(); // return \Magento\Framework\UrlInterface
$context->getMessageManager(); // return \Magento\Framework\Message\ManagerInterface
$context->getResultRedirectFactory(); // return \Magento\Framework\Controller\Result\RedirectFactory
$context->getResultFactory(); // return \Magento\Framework\Controller\ResultFactory

If you need any more help, feel free to contact me. Happy Coding 🙂

Updated: