Last updated November 12, 2013. Created by pcambra on June 24, 2013.
Edited by jhodgdon, Gábor Hojtsy, chx, mbrett5062. Log in to edit this page.

There are several advantages of the service container. Since each service is accessed / instantiated using a single string key and has a defined interface, it can be swapped out with a different implementation. To modify existing services, implement a class extending ServiceProviderBase and the alter() method.

For example, define example/lib/Drupal/example/ExampleServiceProvider.php for a module named example:

<?php
/**
* @file
* Contains Drupal\example\ExampleServiceProvider
*/
namespace Drupal\my_module;
use
Drupal\Core\DependencyInjection\ContainerBuilder;
use
Drupal\Core\DependencyInjection\ServiceProviderBase;
/**
* Modifies the language manager service.
*/
class ExampleServiceProvider extends ServiceProviderBase {
 
/**
   * {@inheritdoc}
   */
 
public function alter(ContainerBuilder $container) {
   
// Overrides language_manager class to test domain language negotiation.
   
$definition = $container->getDefinition('language_manager');
   
$definition->setClass('Drupal\language_test\LanguageTestManager');
  }
}
?>

Note that if you want this service alteration to be recognized automatically, the name of this class is required to be a CamelCase version of your module's machine name, it is required to be in your module's top-level namespace (Drupal\your_module_name), and it must implement \Drupal\Core\DependencyInjection\ServiceModifierInterface (which ServiceProviderBase does).

Other examples of where service swapping may be useful is to swap out the string translation service (the one behind t()). A common feature request that Drupal core does not provide is to have regional language variants or informal/formal languages, where the translation differences may be minimal. By swapping the string translation service, this is easy to resolve in a contributed module.

Finally, it is also possible to define the register() method to register services dynamically, however this should be very rare.

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.