Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

 To modify existing services, implement a class extending ServiceProviderBase and the alter() method. If you want to extend existing services to add functionality, you may also consider decorating the service.

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 followed by ServiceProvider, 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).

 

Example how to override user.auth service:

 

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Class MyModuleServiceProvider.
 *
 * @package Drupal\mymodule
 */
class MyModuleServiceProvider extends ServiceProviderBase
{

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container)
  {
    $definition = $container->getDefinition('user.auth');
    $definition->setClass('Drupal\mymodule\MYCLASS');
    $definition->setArguments(
      [
        new Reference('entity.manager'),
        new Reference('password'),
        new Reference('language_manager'),
        new Reference('logger.factory'),
        new Reference('mymodule.custom_service'),
      ]
    );
  }

}

 

Also you can override core service using mymodule.services.yml

A simpler way to override core service class without creating your custom service provider class.
Following example will override core service named "user.auth".

services:
  user.auth:
    class: Drupal\mymodule\MyUserAuth
    arguments: ['@entity.manager', '@password', '@language_manager', '@logger.factory', '@mymodule.custom_service']

 

Comments

Add new comment

Restricted HTML

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

I am a senior web developer, I have experience in planning and developing large scale dynamic web applications especially in Drupal and Laravel.

Web Posts

Search

Page Facebook