3

how can I access site configuration when in Drush command?

Global variable $config === null and when I use Config::get('key'), I get

Error: Using $this when not in object context in Drupal\Core\Config\Config::get() (line 85 of /var/www/drupalvm/drupal/web/core/lib/Drupal/Core/Config/Config.php)`

What is the recommended approach? I can't find it anywhere... thank you!

Edit

I actually intended to access Settings, not Config - that's where the confusion came from. Settings::get() works just fine. To get data from config, just follow the accepted answer.

3 Answers 3

2

Get is not a static method, so it should not be called statically (using ::). Use Drupal's service container and get the config service using \Drupal::service('config'), then get your config from that.

0
1

Drupal 9

Inject the config factory and the site settings and then you can get all config and settings you need.

# modules/custom/MY_MODULE/drush.services.yml
services:
  MY_MODULE.commands:
    class: \Drupal\MY_MODULE\Commands\MyModuleCommands
    arguments: ['@config.factory', '@settings']
    tags:
      - { name: drush.command }

// modules/custom/MY_MODULE/src/Commands/MyModuleCommands.php
<?php

namespace Drupal\MY_MODULE\Commands;

use Drupal\Core\Site\Settings;
use Drush\Commands\DrushCommands;
use Drupal\Core\Config\ConfigFactoryInterface;

/**
 * Provide Drush commands for MY MODULE.
 */
class MyModuleCommands extends DrushCommands {

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The site settings.
   *
   * @var \Drupal\Core\Site\Settings
   */
  protected $settings;

  /**
   * MyModuleCommands constructor.
   */
  public function __construct(ConfigFactoryInterface $configFactory, Settings $settings) {
    parent::__construct();
    $this->configFactory = $configFactory;
    $this->settings = $settings;
  }

   /**
   * Get stuf
   *
   * @command my:stuff
   * @aliases muff
   * @usage my:stuff
   *   Get stuff from site.settings
   */
  public function getStuff() {

    $uuid = $this->configFactory->get('system.site')->get('uuid');
    $this->logger()->success($uuid);

    $batch_size = $this->settings->get('entity_update_batch_size');
    $this->logger()->success($batch_size);
  }

}
1
  • Does this use values overridden in settings.php? The built in drush cget command sadly does not.
    – liquidcms
    Feb 10 at 16:59
0

Try drush cget configName

Drush config-get Documentation

sample:

drush config-get system.site

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.