Views: 2014
Last Modified: 18.10.2022

Sometimes, there is an objective to cache data, associated with the current user. However, one of available options is to use the session. Extra caution is required, however, since such approach is not always suitable:

  1. session wasn't specifically created for caching,
  2. large data volume affects the sessions speed,
  3. instances of blocked hits occur.

One of alternative approaches is to create a cache, associated with session_id(). In essence, it's a simple session simulation. Starting from main version 20.5.400 there is a new option available.

Example:

$localStorage = \Bitrix\Main\Application::getInstance()->getLocalSession('someCategory');
if (!isset($localStorage['productIds']))
{
    $localStorage->set('productIds', [1, 2, 100]);
    $localStorage->set('price', 42);
}

var_dump($localStorage->get('productIds'));

Basic principle

Operational principle is fairly simple: calling \Bitrix\Main\Application::getLocalSession($name) always returns an instance of \Bitrix\Main\Data\LocalStorage\SessionLocalStorage. This is a cache element that automatically employs session_id().

At this moment, if this is a first query and no data is available, the system creates an empty container. If cache contained data by $name, the container will be filled with data.

All SessionLocalStorage are automatically saved at the end of hit by the kernel.

Attention! SessionLocalStorage operates using cache, described in the .settings.php.

Note: If this is a file-related cache, the SessionLocalStorage will use $_SESSION for storage Otherwise an issue of deleting and verifying legacy files occurs, affecting the file system operation.

Related documentation:



Courses developed by Bitrix24