ReplicaDatabaseIgnoreSubscriber.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace Drupal\Core\EventSubscriber;
  3. use Drupal\Core\Database\Database;
  4. use Symfony\Component\HttpKernel\KernelEvents;
  5. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. /**
  8. * System subscriber for controller requests.
  9. */
  10. class ReplicaDatabaseIgnoreSubscriber implements EventSubscriberInterface {
  11. /**
  12. * Checks and disables the replica database server if appropriate.
  13. *
  14. * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  15. * The Event to process.
  16. */
  17. public function checkReplicaServer(GetResponseEvent $event) {
  18. // Ignore replica database servers for this request.
  19. //
  20. // In Drupal's distributed database structure, new data is written to the
  21. // master and then propagated to the replica servers. This means there is a
  22. // lag between when data is written to the master and when it is available
  23. // on the replica. At these times, we will want to avoid using a replica server
  24. // temporarily. For example, if a user posts a new node then we want to
  25. // disable the replica server for that user temporarily to allow the replica
  26. // server to catch up.
  27. // That way, that user will see their changes immediately while for other
  28. // users we still get the benefits of having a replica server, just with
  29. // slightly stale data. Code that wants to disable the replica server should
  30. // use the db_set_ignore_replica() function to set
  31. // $_SESSION['ignore_replica_server'] to the timestamp after which the replica
  32. // can be re-enabled.
  33. if (isset($_SESSION['ignore_replica_server'])) {
  34. if ($_SESSION['ignore_replica_server'] >= REQUEST_TIME) {
  35. Database::ignoreTarget('default', 'replica');
  36. }
  37. else {
  38. unset($_SESSION['ignore_replica_server']);
  39. }
  40. }
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public static function getSubscribedEvents() {
  46. $events[KernelEvents::REQUEST][] = ['checkReplicaServer'];
  47. return $events;
  48. }
  49. }