Symfony Decorators in Drupal: An Example

By admin, 18 April, 2024

In this Example we decorate the getMessage function of the SessionLimit Service from the Contrib module Session Limit.

  • We first need to identify the class we need to decorate
  • The method we need to decorate
  • write a decorator class 
  • declare service in the custom module services.yml file

*custom_module/src/Serivces/SessionLimitDecorator.php

<?php
    namespace Drupal\custom_module\Services;
    
    use Drupal\Core\Session\AccountInterface;
    use Drupal\session_limit\Services\SessionLimit;
    
    /**
    * Decorator for the SessionLimit service.
    */
    class SessionLimitDecorator extends SessionLimit {
    
      /**
      * Override for the Contrib Module getMessage function
      */
      public function getMessage(AccountInterface $account) {
        return t('Logout due to session limit reached.');
      }
    }

*custom_module.services.yml

custom_module.overide.decorator:
  public: false
  class:\Drupal\intact_core\Services\SessionLimitDecorator
  decorates: session_limit
  decoration_priority: 5
  arguments: ['@database', '@event_dispatcher', '@current_route_match', '@current_user', '@session_manager', '@module_handler', '@config.factory', '@messenger']
  tags:
    - {name: event_subscriber}

References: 

Tags

Stars
Average: 5 (1 vote)

Comments