Magento 2 Tutorial: Cookies, Registry, Session

30 May 2016

magento-dev-company

Sometimes when processing web application requests there is a need in short-term storage of intermediate information. For information storage in client’s browser we use cookies, for data storage within one request – registry, for data storage between requests – sessions.

Here are the examples for Magento 2:

Cookies

Снимок экрана 2016-05-30 в 12.29.20

Registry

Registry allows to use global variables in Magento (although global variables are not welcomed by web developers). Registry throws an exception when attempting to record data with already existing key (if the option is $graceful = false) or just ignores re-record (if $graceful = true).

Снимок экрана 2016-05-30 в 12.41.34

Session

SessionManagerInterface allows to record and read data in/from StorageInterface. Storage is a DataObject and, therefore, for sessions get/set accessors are used (via “magic” method_call):

Снимок экрана 2016-05-30 в 12.49.34

In this example we use default namespace for data storage, so there is a possibility of crossing the names of developers of other modules. In order to reduce this possibility we can add prefixes in variable names creating unique names for methods like setYourCompanyNameReferralCode($data) or use SessionManager’s implementations with related to it SessionStorage with a different namespace.

 

Alina Kulpinska

Alina Kulpinska

Marketing manager and content writer of eLogic. In constant search of creative and innovative ideas for company's development.