Magento – Correct way to obtain a session object

checkoutmagento2session

I'm writing a payment module for Magento 2 right now and I'm checking it against the
"Magento Extension Quality Program Coding Standard" CodeSniffer
(https://github.com/magento/marketplace-eqp).

For every of my classes that are using a (checkout) session object, the CodeSniffer responds with the following warning:

Session object MUST NOT be requested in constructor. It can only be passed as a method argument.

I'm getting the session object in the following way:

/**
 * Checkout session object
 *
 * @var \Magento\Checkout\Model\Session
 */
protected $checkoutSession;

/**
 * Constructor
 *
 * @param  \Magento\Checkout\Model\Session $checkoutSession
 * @return void
 */
public function __construct(\Magento\Checkout\Model\Session $checkoutSession)
{
    $this->checkoutSession = $checkoutSession;
}

Is there a correct way to obtain the session object?
I couldn't find anything in the Magento 2 core code.
I could only find code where it is used in exactly the same way I use it.

Best Answer

Magento Docs are saying

If a class’s constructor is particularly resource-intensive, this can lead to unnecessary performance impact when another class depends on it, if the expensive object does not end up being needed during a particular request.

Magento has a solution for this situation: proxies. Proxies extend other classes to become lazy-loaded versions of them. That is, a real instance of the class a proxy extends is created only after one of the class’s methods is actually called. A proxy implements the same interface as the original class and so can be used as a dependency anywhere the original class can. Unlike its parent, a proxy has only once dependency: the object manager.

Proxies are generated code and therefore do not need to be manually written. (See Code generation for more information.) Simply reference a class in the form \Original\Class\Name\Proxy, and the class is generated if it does not exist.

Magento 2 Proxies

So, in your case

/**
 * Checkout session object
 *
 * @var \Magento\Checkout\Model\Session\Proxy
 */
protected $checkoutSession;

/**
 * Constructor
 *
 * @param  \Magento\Checkout\Model\Session\Proxy $checkoutSession
 * @return void
 */
public function __construct(\Magento\Checkout\Model\Session\Proxy $checkoutSession)
{
    $this->checkoutSession = $checkoutSession;
}

Note \Proxy suffix for the object \Magento\Checkout\Model\Session

Related Topic