Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.

DRUPAL 8 STORAGES OVERVIEW

16 vues

Publié le

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

Publié dans : Formation
  • Soyez le premier à commenter

DRUPAL 8 STORAGES OVERVIEW

  1. 1. Drupal 8Drupal 8 STORAGES OVERVIEWSTORAGES OVERVIEW WHERE BETTER TO STORE OUR DATAWHERE BETTER TO STORE OUR DATA
  2. 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. 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. 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. 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
  6. 6. CONFIG SERVICECONFIG SERVICE services: config.factory: class: DrupalCoreConfigConfigFactory tags: - { name: event_subscriber } arguments: ['@config.storage', '@event_dispatcher', '@config.typed'] config.storage: class: DrupalCoreConfigCachedStorage arguments: ['@config.storage.active', '@cache.config'] config.storage.active: class: DrupalCoreConfigDatabaseStorage arguments: ['@database', 'config'] public: false tags: - { name: backend_overridable } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  7. 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. 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
  9. 9. CONFIG EXAMPLECONFIG EXAMPLE /** @var DrupalCoreConfigConfigFactoryInterface $config_factory */ $config_factory = Drupal::service('config.factory'); $config_editable = $config_factory->getEditable('my_module.test'); $config_editable->set('key_1', 'value_1'); $config_editable->save(); $value = $config_editable->get('key_1'); $config = $config_factory->get('my_module.test'); $value_1 = $config->get('key_1'); 1 2 3 4 5 6 7 8 9
  10. 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. 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).
  12. 12. KEY VALUE SERVICEKEY VALUE SERVICE parameters: factory.keyvalue: default: keyvalue.database services: keyvalue: class: DrupalCoreKeyValueStoreKeyValueFactory arguments: ['@service_container', '%factory.keyvalue%'] keyvalue.database: class: DrupalCoreKeyValueStoreKeyValueDatabaseFactory arguments: ['@serialization.phpserialize', '@database'] 1 2 3 4 5 6 7 8 9 10
  13. 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. 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
  15. 15. KEY VALUE EXAMPLEKEY VALUE EXAMPLE /** @var DrupalCoreKeyValueStoreKeyValueFactoryInterface $key_value */ $key_value = Drupal::service('keyvalue'); /** @var DrupalCoreKeyValueStoreKeyValueStoreInterface $test_collection */ $test_collection = $key_value->get('test_collection'); $test_collection->set('key_1', 10); $value = $test_collection->get('key_1'); $values = $test_collection->getAll(); $test_collection->delete('key_1'); 1 2 3 4 5 6 7 8
  16. 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. 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.
  18. 18. KEY VALUE EXPIRABLE SERVICEKEY VALUE EXPIRABLE SERVICE parameters: factory.keyvalue.expirable: default: keyvalue.expirable.database services: keyvalue.expirable: class: DrupalCoreKeyValueStoreKeyValueExpirableFactory arguments: ['@service_container', '%factory.keyvalue.expirable%'] keyvalue.expirable.database: class: DrupalCoreKeyValueStoreKeyValueDatabaseExpirableFactory arguments: ['@serialization.phpserialize', '@database'] 1 2 3 4 5 6 7 8 9 10
  19. 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
  20. 20. KEY VALUE EXPIRABLE EXAMPLEKEY VALUE EXPIRABLE EXAMPLE /** @var DrupalCoreKeyValueStoreKeyValueExpirableFactoryInterface $key_value */ $key_value = Drupal::service('keyvalue.expirable'); /** @var DrupalCoreKeyValueStoreKeyValueExpirableStoreInterface $test_collection */ $test_collection = $key_value->get('test_collection'); $test_collection->set('key_1', 10); $test_collection->setWithExpire('key_2', 15, 400); $value = $test_collection->get('key_1'); $values = $test_collection->getAll(); $test_collection->delete('key_1'); 1 2 3 4 5 6 7 8 9
  21. 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. 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
  23. 23. STATE SERVICESTATE SERVICE services: state: class: DrupalCoreStateState arguments: ['@keyvalue'] 1 2 3 4
  24. 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
  25. 25. STATE EXAMPLESTATE EXAMPLE /** @var DrupalCoreStateStateInterface $state */ $state = Drupal::service('state'); $state->set('my_module.key_1', 'value_1'); $value = $state->get('my_module.key_1'); $state->delete('my_module.key_1'); 1 2 3 4 5
  26. 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.
  27. 27. USER PRIVATE TEMPSTORE SERVICEUSER PRIVATE TEMPSTORE SERVICE parameters: tempstore.expire: 604800 # 7 days services: tempstore.private: class: DrupalCoreTempStorePrivateTempStoreFactory arguments: ['@keyvalue.expirable', '@lock', '@current_user', '@request_stack', tags: - { name: backend_overridable } 1 2 3 4 5 6 7 8
  28. 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
  29. 29. USER PRIVATE TEMPSTORE EXAMPLEUSER PRIVATE TEMPSTORE EXAMPLE /** @var DrupalCoreTempStorePrivateTempStoreFactory $temp_store */ $temp_store = Drupal::service('tempstore.private'); /** @var DrupalCoreTempStorePrivateTempStore $test_collection */ $test_collection = $temp_store->get('test_collection'); $node = Node::create([ 'type' => 'article', 'title' => 'Article Title', ]); $test_collection->set('article', $node); $node = $test_collection->get('article'); $node->save(); $test_collection->delete('article'); 1 2 3 4 5 6 7 8 9 10 11 12 13
  30. 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. 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.
  32. 32. USER SHARED TEMPSTORE SERVICEUSER SHARED TEMPSTORE SERVICE parameters: tempstore.expire: 604800 # 7 days services: tempstore.shared: class: DrupalCoreTempStoreSharedTempStoreFactory arguments: ['@keyvalue.expirable', '@lock', '@request_stack', '%tempstore.expi tags: - { name: backend_overridable } 1 2 3 4 5 6 7 8
  33. 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
  34. 34. USER SHARED TEMPSTORE EXAMPLEUSER SHARED TEMPSTORE EXAMPLE /** @var DrupalCoreTempStoreSharedTempStoreFactory $temp_store */ $temp_store = Drupal::service('tempstore.shared'); /** @var DrupalCoreTempStoreSharedTempStore $test_collection */ $test_collection = $temp_store->get('test_collection'); $data = [ 'key_1' => 'value_1', 'key_2' => 'value_2', ]; $test_collection->set('options', $data); $options = $test_collection->get('options'); 1 2 3 4 5 6 7 8 9 10 11
  35. 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. 36. CACHECACHE Uses for storing information which is also stored somewhere else. Caches exist only to speed up data retrieval.
  37. 37. CACHE SERVICESCACHE SERVICES services: cache_factory: class: DrupalCoreCacheCacheFactory arguments: ['@settings', '%cache_default_bin_backends%'] calls: - [setContainer, ['@service_container']] cache.backend.chainedfast: class: DrupalCoreCacheChainedFastBackendFactory arguments: ['@settings'] calls: - [setContainer, ['@service_container']] cache.backend.database: class: DrupalCoreCacheDatabaseBackendFactory arguments: ['@database', '@cache_tags.invalidator.checksum', '@settings'] # Cache bins 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
  38. 38. CACHE FACTORYCACHE FACTORY DrupalCoreCacheCacheFactoryInterface Name Description get($bin) DrupalCoreCacheCacheBackendInterface
  39. 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
  40. 40. CACHE EXAMPLECACHE EXAMPLE /** @var DrupalCoreCacheCacheFactoryInterface $cache_factory */ $cache_factory = Drupal::service('cache_factory'); /** @var DrupalCoreCacheCacheBackendInterface $cache */ $cache = $cache_factory->get('default'); $data = [ 'key_1' => 'value_1', 'key_2' => 'value_2', ]; $tags = ['node_list', 'user_list']; $cache->set('my_module.settings', $data, Cache::PERMANENT, $tags); $value = $cache->get('my_module.settings'); 1 2 3 4 5 6 7 8 9 10 11
  41. 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. 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.
  43. 43. SESSION EXAMPLESESSION EXAMPLE public function storeGroupInput($input, $status) { if (empty($this->options['group_info']['remember'])) { return; } $view_id = $this->storage->id(); $display_id = $this->current_display; if ( $status === FALSE && isset($_SESSION['views'][$view_id][$display_id]) ) { $session = &$_SESSION['views'][$view_id][$display_id]; } if ($status !== FALSE) { if (!isset($_SESSION['views'][$view_id][$display_id])) { $_SESSION['views'][$view_id][$display_id] = []; } $session = &$_SESSION['views'][$view_id][$display_id]; $filter_id = $this->options['group_info']['identifier']; $session[$filter_id] = $input[$filter_id]; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
  44. 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. 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
  46. 46. THANK YOU FOR ATTANTIONTHANK YOU FOR ATTANTION
  47. 47. SOURCESSOURCES https://www.palantir.net/blog/d8ftw-storing-data-drupal-8 https://www.anubavam.com/blogs/how-store-session-data-drupal-8 https://www.drupal.org/docs/8/api/state-api/overview https://www.drupal.org/docs/8/api/con guration-api/con guration-api-overview https://www.drupal.org/docs/8/api/con guration-api/overview-of-con guration-vs-other-types-of-information https://www.drupal.org/docs/8/api/con guration-api/con guration-storage-in-drupal-8 https://antistatique.net/en/we/blog/2016/06/14/drupal-8-differences-between-con guration-api-state-api https://www.valuebound.com/resources/blog/a-beginners-guide-to-caching-drupal-8

×