variable_get and variable_set in Drupal 8

variable_get and variable_set in Drupal 8

variable_get()/variable_set() and variable_del() API was removed from Drupal 8 in favor of Configuration API.

So in order to save a simple variable in your module firstly you need to decide on a config object name and a name for the settings. Simple settings can be stored in a config object named <module_name>.settings, while for more complex settings it is advisable to use sub-keys.

To get a variable in Drupal 7 you would use:

$site_name = variable_get('site_name', '');

While in Drupal 8 instead of variable_get we use Drupal config:

$site_name = \Drupal::config('system.site')->get('name');

or if you are working within a context of a class:

$site_name = $this->config('system.site')->get('name');

To set a variable, in Drupal 7 was:

variable_set('mymodule_setting', 'myfirstvariable');

While in Drupal 8 instead of variable_set we use Drupal config:

\Drupal::config('mymodule.settings')
      ->set('mysettingname', 'myfirstvariable')
      ->save();