R
Rajesh Patra
Back to Blog

How to use Defined Methods of Context Object in Magento 2

0 views
0 likes
How to use Defined Methods of Context Object in Magento 2

In this article, we are going to know about the Context Object in Magento 2 and how to use the defined methods of the Context Object in your Magento 2 module.

What is a Context Object in Magento 2?

A Context Object is an object which has several constructor dependencies and getters of other objects. It works like a container for other objects. A context object doesn't have any functionality of its own — it's just a container for other objects.

Types of Context Objects

There are different context objects used for different parts of Magento 2.

1. Context Object in a Magento 2 Block

In a Magento 2 block, the class of the context object is \Magento\Framework\View\Element\Template\Context. The constructor of a Magento block class looks like this.

php
public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    array $data = []
) {
    parent::__construct($context, $data);
}

2. Context Object in a Magento 2 Helper

In a Magento 2 helper, the class of the context object is \Magento\Framework\App\Helper\Context. The constructor of a Magento helper class looks like this.

php
public function __construct(
    \Magento\Framework\App\Helper\Context $context
) {
    parent::__construct($context);
}

3. Context Object in a Magento 2 Model

In a Magento 2 model, the class of the context object is \Magento\Framework\Model\Context. This context object can be used in the constructor of a Magento model class like this, along with other required objects and dependencies.

php
public function __construct(
    \Magento\Framework\Model\Context $context
) {
    $this->context = $context;
}

4. Context Object in a Magento 2 Controller

In a Magento 2 controller, the class of the context object is \Magento\Framework\App\Action\Context. This context object can be used in the constructor of a Magento controller action class like this, along with other required objects and dependencies.

php
public function __construct(
    \Magento\Framework\View\Result\PageFactory $resultPageFactory,
    \Magento\Framework\App\Action\Context $context
){
    $this->resultPageFactory = $resultPageFactory;
    $this->context = $context;
}

How to use the Defined Methods from the Context Object

Since the context object works as a container for other objects, it can be used to access those objects and their methods.

For example, if you need to fetch store configurations in your block, by the most common practice of DI (Dependency Injection), you will inject the \Magento\Framework\App\Config\ScopeConfigInterface class in the constructor like this:

php
public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
    array $data = []
) {
    $this->_scopeConfig = $scopeConfig;
    parent::__construct($context, $data);
}

Although this code will work, it's not correct and not necessary to inject this class in the constructor, because the $context object already contains the object of the \Magento\Framework\App\Config\ScopeConfigInterface class.

While compiling the above code using the bin/magento setup:di:compiler command, sometimes this type of error occurs: "Incorrect dependency in class".

So, instead of injecting the class to the constructor, the correct way is to directly use the defined methods of the context object to fetch the objects of the contained classes. The correct way to call \Magento\Framework\App\Config\ScopeConfigInterface in the above example is this:

php
public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    array $data = []
) {
    $this->_scopeConfig = $context->getScopeConfig();
    parent::__construct($context, $data);
}

List of Methods from Context Object

1. Methods from Context Object in Block

php
$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

2. Methods from Context Object in Helper

php
$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

3. Methods from Context Object in Model

php
$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

4. Methods from Context Object in Controller

php
$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

I hope this article is helpful for you.

MagentoPHP