Overview of the main ways to store data in Drupal 8 depending on data and needs. A detailed description of each way and examples of how to work with storages.
https://drupalcampkyiv.org/node/44
1. Drupal 8Drupal 8
STORAGES OVERVIEWSTORAGES OVERVIEW
WHERE BETTER TO STORE OUR DATAWHERE BETTER TO STORE OUR DATA
2. ABOUT MEABOUT ME
ROMAN HRYSHKANYCHROMAN HRYSHKANYCH
Software Engineer at EPAM Systems
2,5 years in the IT industry and Drupal.
I`m perfectionist, so I prefer to do my work
qualitatively and I enjoy my work.
drupal.org/u/romixua
github.com/romixua
3. PRESENTATION IDEAPRESENTATION IDEA
$config = Drupal::configFactory()->getEditable('module_widget.settings');
if (time() >= $config->get('next_execution')) {
$config->set('next_execution', time() + $interval)->save();
/**1
* Implements hook_cron().2
*/3
function module_cron() {4
5
// Default to a daily interval.6
$interval = $config->get('interval');7
// We usually don't want to act every time cron runs (which could be every8
// minute) so keep a time for the next run in a variable.9
10
// ...11
// Set the next time this hook_cron should be invoked.12
13
}14
}15
4. CONTENT ENTITYCONTENT ENTITY
Content in Drupal 8 means the Entity API. Drupal
Entities are much rigidly structured. There are three
layers to the Entity API, conceptually:
Entity type
Entity bundle
Field
5. CONFIGURATIONCONFIGURATION
The Con guration system replaces the variables table,
the features module, half of the ctools module suite,
and the myriad custom tables that various modules
de ned in previous versions with a single, coherent,
robust way to store, manage, and deploy administrator-
provided con guration. All con gs stored in “con g”
database table and can be exported into (imported
from) YML les. According to the best practice con g
better name: module_name.con g_name
7. CONFIG FACTORYCONFIG FACTORY
DrupalCoreCon gCon gFactoryInterface
Name Description
get($name) DrupalCoreCon gImmutableCon g
getEditable($name) DrupalCoreCon gCon g
loadMultiple($names) DrupalCoreCon gImmutableCon g[]
rename($old_name, $new_name) Rename con gs
listAll($pre x = '') Return array of con g names
addOverride($con g_factory_override) Adds con g factory override services
8. CONFIG OBJECTCONFIG OBJECT
DrupalCoreCon gCon g (ImmutableCon g)
Name Description
get($key = '') Gets data from this con guration object
set($key, $value) Sets a value in this con guration object (Exception in immutable)
setData(array $data) Replaces the data of this con guration object
merge(array $data_to_merge) Merges data into a con guration object.
clear($key) Unsets a value in this con guration object (Exception in immutable)
delete() Deletes the con guration object (Exception in immutable)
save() Saves the con guration object (Exception in immutable)
getRawData() Gets the raw data without overrides
getCacheTags() The cache tags associated with this con g
10. CONFIG IN DATABASECONFIG IN DATABASE
Data stored in database table ‘con g’
collection name data
my_module.test [BLOB - 32 B]
core.extension [BLOB - 1.2 KB]
user.settings [BLOB - 604 B]
language.uk user.settings [BLOB - 42 B]
11. KEY VALUEKEY VALUE
Key value – is a storage, that consist from collections,
and can store values of any type, as they will be
serialized and unserialized automatically (However, not
all object types can be serialized).
13. KEY VALUE FACTORYKEY VALUE FACTORY
DrupalCoreKeyValueStoreKeyValueFactoryInterface
Name Description
get($collection) DrupalCoreKeyValueStoreKeyValueStoreInterface
All key value factories consist of gust one method –
get(), which returns collection object.
14. KEY VALUE STORAGEKEY VALUE STORAGE
DrupalCoreKeyValueStoreKeyValueStoreInterface
Name Description
getCollectionName() Returns the name of this collection
has($key) Check if key exists in the collection
get($key) Return collection item value
getMultiple($keys) Return collection multiple item values
getAll() Returns all stored key/value pairs in the collection
set($key, $value) Saves a value for a given key
setIfNotExists($key, $value) Saves a value for a given key if it does not exist yet
setMultiple($data) Saves key/value pairs.
rename($key, $new_key) Renames a key
delete($key) Deletes an item from the key/value store
deleteMultiple($keys) Deletes multiple items from the key/value store
deleteAll() Deletes all items from the key/value store
16. KEY VALUE IN DATABASEKEY VALUE IN DATABASE
Data stored in database table ‘key_value’
collection name data
system.schema taxonomy [BLOB - 7 B]
system.schema text [BLOB - 7 B]
system.schema user [BLOB - 11 B]
state system.private_key [BLOB - 82 B]
state system.cron_last [BLOB - 13 B]
17. KEY VALUE EXPIRABLEKEY VALUE EXPIRABLE
Key value expirable – is a similar to key value storage
but values will get cleared, when key value age is over.
19. KEY VALUE EXPIRABLE STORAGEKEY VALUE EXPIRABLE STORAGE
Key value expirable factory also have just one get($collection) function,
which returns Key value expirable storage
DrupalCoreKeyValueStoreKeyValueStoreExpirableInterface
Key value store expirable additional functions
Name Description
setWithExpire($key, $value, $expire) Saves a value for a given key with a time to live
setWithExpireIfNotExists($key, $value, $expire) Sets a value with a time to live if it does not yet exist
setMultipleWithExpire($data, $expire) Saves an array of values with a time to live
* $expire - the time to live for items, in seconds
21. KEY VALUE EXPIRABLE IN DATABASEKEY VALUE EXPIRABLE IN DATABASE
Data stored in database table ‘key_value_expirable’
collection name data expire
test_collection key_1 [BLOB - 5 B] 2147483647
test_collection key_2 [BLOB - 5 B] 1548746620
22. STATESTATE
Storage for storing information about the system's
state, based on key value collection ‘state’. In state are
stored: last crone execution time, site install time,
system private key, etc. State storage also work in pair
with bootstrap cache, that improves performance and
prevent a huge number of database queries. Cache will
be created after value get, and will be invalidated after
value set. Best practice for keys name is –
module_name.key_name
24. STATE STORAGESTATE STORAGE
DrupalCoreStateStateInterface
Name Description
get($key) Returns the stored value for a given key
getMultiple($keys) Returns the stored key/value pairs for a given set of keys
set($key, $value) Saves a value for a given key
setMultiple($data) Saves key/value pairs
delete($key) Deletes an item
deleteMultiple($keys) Deletes multiple items
resetCache() Resets the static cache
26. USER PRIVATE TEMPSTOREUSER PRIVATE TEMPSTORE
Store based on key value expirable storage. For one key
value is individual for each user. The mostly uses for
multiple steps forms, previews before saving and
con rmation forms.
28. USER PRIVATE TEMPSTOREUSER PRIVATE TEMPSTORE
DrupalCoreTempStorePrivateTempStoreFactory
User private tempstore factory have just one get($collection) function,
which returns private temp store
DrupalCoreTempStorePrivateTempStore
Name Description
get($key) Retrieves a value from this PrivateTempStore for a given key
set($key, $value) Stores a particular key/value pair in this PrivateTempStore.
getMetadata($key) Returns the metadata associated with a particular key/value pair
delete($key) Deletes data from the store for a given key
30. USER PRIVATE TEMPSTORE IN DATABASEUSER PRIVATE TEMPSTORE IN DATABASE
Data stored in database table ‘key_value_expirable’
collection name data expire
tempstore.private.test_collection 1:article [BLOB - 2.5 KB] 1559266848
tempstore.private.test_collection w7bNdnm0Us:article [BLOB - 2.5 KB] 1559267088
31. USER SHARED TEMPSTOREUSER SHARED TEMPSTORE
As a user private temp store also based on key value
expirable storage. The value is one for all user, but also
records key value pair owner. he mostly uses view, page
manager, search index elds changes before saving.
33. USER SHARED TEMPSTOREUSER SHARED TEMPSTORE
DrupalCoreTempStoreSharedTempStoreFactory
User shared tempstore factory have just one get($collection) function,
which returns shared temp store
DrupalCoreTempStoreSharedTempStore
Shared temp store additional functions
Name Description
getIfOwner($key) Retrieves a value from this SharedTempStore if the value is owned by this user
setIfOwner($key, $value) Set a value to SharedTempStore if it does not exist yet or is owned by this user
35. USER SHARED TEMPSTORE IN DATABASEUSER SHARED TEMPSTORE IN DATABASE
Data stored in database table ‘key_value_expirable’
collection name data expire
tempstore.shared.test_collection options [BLOB - 135 B] 1559279349
tempstore.shared.views news [BLOB - 10.8 KB] 1559281791
36. CACHECACHE
Uses for storing information which is also stored
somewhere else. Caches exist only to speed up data
retrieval.
39. CACHE BINCACHE BIN
DrupalCoreCacheCacheBackendInterface
Name Description
get($cid) Returns data from the persistent cache
getMultiple($cids) Returns data from the persistent cache from array of cache IDs
set($cid, $data, $expire = -1, $tags = []) Stores data in the persistent cache
setMultiple($items) Store multiple items in the persistent cache
delete($cid) Deletes an item from the cache
deleteMultiple($cids) Deletes multiple items from the cache
deleteAll() Deletes all cache items in a bin
invalidate($cid) Marks a cache item as invalid
invalidateMultiple(array $cids) Marks cache items as invalid
invalidateAll() Marks all cache items as invalid
garbageCollection() Performs garbage collection on a cache bin
removeBin() Remove a cache bin
41. CACHE BIN IN DATABASECACHE BIN IN DATABASE
Data stored in database table ‘cache_[bin name]’
cid data expire created serialized tags checksum
my_module.settings [BLOB - 58 B] -1 1558697024.380 1 node_list user_list 19
system.module.info [BLOB - 41.5 kB] -1 1558697022.429 1 node_list user_list 0
42. SESSIONSESSION
Using 'session' database table, also can store inside
different types of data, including ojects. This data
alwasy reads and writes durring each requsest.
44. SESSION IN DATABASESESSION IN DATABASE
Data stored in database table ‘session’
uid sid hostname timestamp session
1 2abhmLE-98a4wRGPOjf252Eun9KvnucJERjEuMP50XM 127.0.0.1 1558684777 [BLOB - 179 B]
0 tm_ej0wNUjeF9suW0vdwjihXPJcMDah2n37oupb6v-U 127.0.0.1 1558662288 [BLOB - 159 B]
45. CONCLUSIONCONCLUSION
Structured data, which can be created by users, different on each environment and
should have ability to search data by different conditions - content entity
This data are already stored somewhere, but we need to improve performance
during receiving of this data - cache
Some system property that should be different on each environment - state
Some settings that should be deployed to all environment - con guration
Temporary data, that should be accessible by key and individual for each user -
private tempstore
Permanent data, that should be accessible by key and different on each
environment - key value