I'm using event dispatcher in a custom module to auto login users in a Drupal 8 website. I'm using the KernelEvents::REQUEST, with a onRequest fonction. I put an echo for testing that the function was call :
- When the user is already log in, the event work and my function was call on every request
- When the user IS NOT log in (anonymous), the function was call on the only first request of a page. Never call again if you reload the page. Only way to get my echo again is to empty drupal cache (I make a drush cr).
Don't know exactly how Drupal cache work... Is there any way to trigger my event on every request, anonymous or not ? Or another better way to do my auto login ? Thanks.
my module structure :
/mymodule
|-- /src
|---- /Controller
|------ MyModuleController.php
|---- /EventSubscriber
|------ MyModuleEventSubscriber.php
mymodule.info.yml
mymodule.routing.yml
mymodule.services.yml
MyModuleEventSubscriber.php
<?php
namespace Drupal\mymodule\EventSubscriber;
use Drupal\Core\Routing\ResettableStackedRouteMatchInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\externalauth\ExternalAuthInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\RedirectResponse;
class MyModuleEventSubscriber implements EventSubscriberInterface {
protected $currentRouteMatch;
protected $externalauth;
protected $currentUser;
/**
* Constructs a MyModuleEventSubscriber object.
*/
public function __construct(ResettableStackedRouteMatchInterface $currentRouteMatch, ExternalAuthInterface $externalauth, AccountProxyInterface $currentUser) {
$this->currentRouteMatch = $currentRouteMatch;
$this->externalauth = $externalauth;
$this->currentUser = $currentUser;
}
/**
* Implements EventSubscriberInterface::getSubscribedEvents().
*
* @return array
* An array of event listener definitions.
*/
static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = array('onRequest');
return $events;
}
public function onRequest(GetResponseEvent $event) {
// echo 'test' => do my echo here
if ($this->currentUser->id() == '0') {
auto_login(); // I simplified the code here, but you get the idea
}
}
}
mymodule.services.yml
services:
mymodule.event_subscriber:
class: Drupal\mymodule\EventSubscriber\MyModuleEventSubscriber
arguments: ['@current_route_match', '@externalauth.externalauth', '@current_user']
tags:
- { name: event_subscriber }