How to change core's default services

by Andy Truong   Last Updated April 19, 2018 22:07 PM

Dependency Injection is added to core, but there's no documentation to tell how developer can alter the default services. For example, I would like to change cache.bootstrap class to APC Caching.



Answers 1


You can look at LanguageTestServiceProvider to see how alterations are made. Or I can offer my class:

<?php
namespace Drupal\mongodb;

use Drupal\Core\DependencyInjection\ServiceModifierInterface;
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;

/**
 * MongoDB service provider. Registers Mongo-related services.
 */
class MongodbServiceProvider implements ServiceProviderInterface, ServiceModifierInterface {

  /**
   * {@inheritdoc}
   */
  public function register(ContainerBuilder $container) {
  }

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    foreach ($container->findTaggedServiceIds('mongodb.override') as $id => $attribute) {
      $container->setDefinition(substr($id, 8), $container->getDefinition($id));
    }
  }

}

Basically, in alter you need to use the getDefinition method, do something with the definition and then use the setDefinition method to put it back.

and then here's the relevant parts of mongodb.services.yml:

services:
  mongodb.flood:
    class: Drupal\mongodb\Flood\MongoDBBackend
    arguments: ['@mongo', '@request']
    tags:
      - { name: mongodb.override }
user49
user49
September 28, 2013 09:57 AM

Related Questions



How to resolve my warning in my custom service?

Updated April 19, 2018 07:07 AM


Concept of services, tags, and arguments

Updated April 19, 2018 11:07 AM

Service function is not calling

Updated April 19, 2018 12:07 PM