8

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.

5
  • 1
    Oh but there is :)
    – Clive
    Sep 28, 2013 at 0:25
  • Aw, my fault. I am sorry. Sep 28, 2013 at 0:28
  • No need to apologise, unless you know it's done using compiler passes I think that would be pretty hard to find. If you get a chance please do add an answer with the code you end up using, I'm sure it will be very useful to future visitors. If not I'll try to remember to come back and add something generic in
    – Clive
    Sep 28, 2013 at 0:38
  • It's no longer done using compiler passes.
    – user49
    Sep 28, 2013 at 10:07
  • The answer by @chx is perfect, but note that your example is a special case. I suggest you open a separate question on how to provide a different cache backend and we can answer that in detail.
    – Berdir
    Sep 28, 2013 at 10:18

1 Answer 1

5

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 }
1
  • Just wanted to mention it looks like you don't need to use setDefintion() if you've used getDefinition() - you can just update the definition.
    – Andy
    Feb 16, 2019 at 10:37

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.