3

I'm writing a module that makes calls to a Web service to read and store data. Here's my services.yml file:

services:
  example.connection:
    class: Drupal\Core\Http\Client

I've already a settings form (inheriting from ConfigFormBase) that stores a base URL in configuration, and I'd like to pass that as an argument to the Client class's constructor. I've tried this:

class ExampleServiceProvider implements ServiceModifierInterface {

  /**
   * Modifies existing service definitions.
   *
   * @param ContainerBuilder $container
   *   The ContainerBuilder whose service definitions can be altered.
   */
  public function alter(ContainerBuilder $container) {
    $base_url = $container->get('config.factory')
        ->get('example_entity.settings')->get('base_url');
    if ($base_url) {
      $arguments = array('base_url' => $base_url);
      $container->getDefinition('example.connection')
        ->setArguments(array($arguments));
    }
  }
}

But that gives me HTTP 403 errors for every page on the site. Should it be possible to pass arbitrary arguments like this? Hardcoding a URL into the $base_url variable works fine.

3
  • The recommended way is to pass in the config.factory as dependency to the actual service. In the service then pull the values from here. One reason for this is that config might be altered dynamically. Jun 1, 2014 at 21:13
  • Agreed. Also it seems like having a ClientFactory as a service instead would be useful, as you could inject both factories and then create the Client with the config. That would require a core issue. Jun 2, 2014 at 0:04
  • @daniel-wehner Thanks! I ended up creating a connection_factory service with a ClientFactory class and passing the config.factory service in as an argument, similar to the final example on the Symfony documentation page Using A Factory To Create Services, which I hadn't discovered up until now.
    – djevans
    Jun 2, 2014 at 10:55

1 Answer 1

2

In your services file add the following service:

# The bar configuration for the foo module
config.foo.bar.immutable:
  class: \Drupal\Core\Config\ImmutableConfig
  factory: config.factory:get
  arguments: ['bar']
config.foo.bar.mutable:
  class: \Drupal\Core\Config\Config
  factory: config.factory:getEditable
  arguments: ['bar']

In your service create method add either config.foo.bar.immutable or config.foo.bar.mutable service as an argument.

Your Answer

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

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