As a Magento developer, you must have seen, in most of the Constructors of Magento 2 classes, a $context object is passed. For example:
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:
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:
Now, let’s see the list of methods in $context object for different classes:
Block Class
Model Class
Helper Class
Controller Class
If you need any more help, feel free to contact me. Happy Coding 🙂
Learn how to create custom shipping methods in Magento 2 with this step-by-step developer’s guide. Enhance your Magento store with personalized shipping opti...
Learn the differences between observers and plugins in Magento 2, and understand when to use each for customization. A comprehensive guide for developers.
Discover how to boost Magento 2 performance using Redis caching. Learn what Redis is, how it works, and how to configure it for enhanced speed and scalabilit...