23

In most of the class's Constructors, a Context object is passed . I couldn't understand how this Context Obj works . I also noticed that sometimes this is passed to parent class's constructor like below.

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

Can you please explain how this specific context object works ?

30

Note that there are different Context objects, in this case it's \Magento\Framework\App\Action\Context and to understand it, you should read it as "ActionContext". It represents the application context in which the action is executed. In other 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 20 parameters in each controller action. All common parameters are merged in the context object.

  • how could i know which object are contained by different $context? – LucScu Jun 9 '16 at 6:48
  • @LucaS look at their source code. You find the contained classes in the context constructor – Fabian Schmengler Jun 9 '16 at 7:22
15

Context objects were introduced to isolate third party developers from changes in constructors of abstract classes.

In Magento 1 Abstract classes with a lot of "helper" behaviour were considered a convenient API for class extender. This caused huge numbers of methods and implicit dependencies in abstract classes (AbstractModel, AbstractBlock, AbstractAction)

In Magento 2 inheritance-based APIs (more precisely SPIs) are discouraged, but many legacy APIs still exist. Initially we planned to gradually remove extra behaviour from abstract classes. And to not break all extenders when we would remove some dependency from constructor, we introduced Context objects.

Current plan is to abandon inheritance-based APIs with interface-based APIs at some point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.