Views: 3071
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:
- session wasn't specifically created for caching,
- large data volume affects the sessions speed,
- 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.
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.