How do I dynamically change cookie_lifetime?
質問
I'm trying to change cookie_lifetime dynamically in my D8 project, to set cookie_lifetime to 0 or to some value(for example 24 hours). I know that this can be partially acomplished by changing cookie_lifetime variable in sites/default/services.yml, but this is not my case.
I've tried to use this answer but looks like it works only when I use start() method of the session manager.
So how do I change dynamically cookie_lifetime for existing session? Any answers appreciated, thanks in advance!
解決
You can override SessionConfiguration::getOptions to set the cookie lifetime dynamically:
/mymodule/src/MySessionConfiguration.php:
<?php
namespace Drupal\mymodule;
use Drupal\Core\Session\SessionConfiguration;
use Symfony\Component\HttpFoundation\Request;
/**
* Sets session cookie lifetime dynamically.
*/
class MySessionConfiguration extends SessionConfiguration {
/**
* {@inheritdoc}
*/
public function getOptions(Request $request) {
$options = parent::getOptions($request);
// Set the cookie lifetime dynamically depending on the request.
$options['cookie_lifetime'] = 30;
return $options;
}
}
Swap the service class in the container:
/mymodule/src/MymoduleServiceProvider.php:
<?php
namespace Drupal\mymodule;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
/**
* Modifies the service.
*/
class MymoduleServiceProvider extends ServiceProviderBase {
/**
* {@inheritdoc}
*/
public function alter(ContainerBuilder $container) {
$definition = $container->getDefinition('session_configuration');
$definition->setClass('Drupal\mymodule\MySessionConfiguration');
}
}
所属していません drupal.stackexchange