Recently, I had to decorate the drupal state service to do something when a site goes into maintenance mode.
When trying to figure out how to do this, I found a really helpful post describing how to decorate the state, by Previous Next. This post was already quite old, and I could not get it to work with the just the information in that post.
First of all, we need to define the service in the services.yml
.
The key to making this work is to having a decorates
key in the service definition.
That makes the new service wrap around the configured service.
hoth.state:
class: Drupal\hoth\State
decorates: state
arguments: ['@keyvalue', '@rebels.notification']
Now all that is needed, is to create the state decorator.
<?php
namespace Drupal\hoth;
use \Drupal\Core\State as CoreState;
class State extends CoreState {
public function __construct(KeyValueFactoryInterface $key_value_factory, RebelNotification $rebelNotification) {
parent::__construct($key_value_factory);
$this->notify = $rebelNotification;
}
public function set($key, $value) {
parent::set($key, $value);
if ($key === 'system.maintenance_mode') {
$this->notify->soundAlarm();
}
}
}
The injected service (RebelNotification
) here can now sound an alarm so that the rebels know about the maintenance mode event.