You are here

public function Container::set in Service Container 7

Same name in this branch
  1. 7 lib/Drupal/Core/DependencyInjection/Container.php \Drupal\Core\DependencyInjection\Container::set()
  2. 7 lib/Drupal/Component/DependencyInjection/Container.php \Drupal\Component\DependencyInjection\Container::set()
  3. 7 modules/providers/service_container_symfony/lib/Symfony/Component/DependencyInjection/Container.php \Symfony\Component\DependencyInjection\Container::set()
Same name and namespace in other branches
  1. 7.2 modules/providers/service_container_symfony/lib/Symfony/Component/DependencyInjection/Container.php \Symfony\Component\DependencyInjection\Container::set()

Sets a service.

Setting a service to null resets the service: has() returns false and get() behaves in the same way as if the service was never created.

@api

Parameters

string $id The service identifier:

object $service The service instance:

string $scope The scope of the service:

Throws

RuntimeException When trying to set a service in an inactive scope

InvalidArgumentException When trying to set a service in the prototype scope

2 calls to Container::set()
Container::leaveScope in modules/providers/service_container_symfony/lib/Symfony/Component/DependencyInjection/Container.php
This is called to leave the current scope, and move back to the parent scope.
ContainerBuilder::set in lib/Drupal/Core/DependencyInjection/ContainerBuilder.php
Overrides Symfony\Component\DependencyInjection\ContainerBuilder::set().

File

modules/providers/service_container_symfony/lib/Symfony/Component/DependencyInjection/Container.php, line 192

Class

Container
Container is a dependency injection container.

Namespace

Symfony\Component\DependencyInjection

Code

public function set($id, $service, $scope = self::SCOPE_CONTAINER) {
  if (self::SCOPE_PROTOTYPE === $scope) {
    throw new InvalidArgumentException(sprintf('You cannot set service "%s" of scope "prototype".', $id));
  }
  $id = strtolower($id);
  if ('service_container' === $id) {

    // BC: 'service_container' is no longer a self-reference but always
    // $this, so ignore this call.
    // @todo Throw InvalidArgumentException in next major release.
    return;
  }
  if (self::SCOPE_CONTAINER !== $scope) {
    if (!isset($this->scopedServices[$scope])) {
      throw new RuntimeException(sprintf('You cannot set service "%s" of inactive scope.', $id));
    }
    $this->scopedServices[$scope][$id] = $service;
  }
  $this->services[$id] = $service;
  if (method_exists($this, $method = 'synchronize' . strtr($id, $this->underscoreMap) . 'Service')) {
    $this
      ->{$method}();
  }
  if (null === $service) {
    if (self::SCOPE_CONTAINER !== $scope) {
      unset($this->scopedServices[$scope][$id]);
    }
    unset($this->services[$id]);
  }
}