Drupal 8 override: services and plugins

Embed Size (px)

Text of Drupal 8 override: services and plugins

  • Drupal 8 override:services and pluginsAnton Ivanov

  • Services override

  • Easiest way #1Copy: /sites/default/default.services.ymlTo: /sites/default/services.ymlPut service definition:

    services: cache_tags.invalidator.checksum: class: Drupal\my_module\Cache\MyModuleCacheTagsChecksum tags: - { name: cache_tags_invalidator }

  • It works becauseIn /sites/default/settings.php available:

    $settings['container_yamls'][] = $app_root . '/' . $site_path . '/services.yml';

    Means: /sites/default/services.yml

  • Easiest way #1.5$settings['container_yamls'][] = 'modules/my_module/example.services.yml';To: /sites/default/settings.phpPut service definition to:example.services.yml

  • Specific of usageAdvantages:Not overridable

    Disadvantages:Not overridableShould update settings.php

  • Way #2If module name is my_moduleCreate /src/MyModuleServiceProvider.php

    class MyModuleServiceProvider extends ServiceProviderBase { public function alter(ContainerBuilder $container) { $definition = $container->getDefinition('language_manager'); $definition ->setClass('Drupal\my_module\MyModuleLanguageManager') ->setArguments([ new Reference('language.default'), new Reference('config.factory'), new Reference('module_handler'), new Reference('language.config_factory_override'), new Reference('request_stack'), new Reference('my_module.handler'), ]); }}

  • Way #2 possible issueCode is correct but not worksAny ideas ?

  • Way #2 issue solutionCode is correct but not worksOverride by another module is lastModule weight is the clue !To hook_install() add: module_set_weight('my_module', 10);

  • Plugins override

  • How to override pluginsFind plugin manager firstIf extends DefaultPluginManagerAnd call alterInfo() in __construct()Use hook_TYPE_alter()

    function my_module_alterhook_alter(&$definitions) { // Do alter here.}

  • Useful linkshttps://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services

    https://www.previousnext.com.au/blog/overriding-services-drupal-8-advanced-cases

    https://api.drupal.org/api/drupal/core!core.api.php/group/plugin_api

    https://www.drupal.org/docs/8/api/plugin-api/plugin-api-overview

  • Thank you! Questions?Anton Ivanov