Late answering, but it's worth mentioning that you can use private tempstore for anonymous users, as long as the tempstore has access to an active session. To do so, you need to inject your class with services for the temp store, session, and current user, like so:
public function __construct(PrivateTempStoreFactory $temp_store_factory, SessionManagerInterface $session_manager, AccountInterface $current_user) {
$this->tempStoreFactory = $temp_store_factory;
$this->sessionManager = $session_manager;
$this->currentUser = $current_user;
$this->store = $this->tempStoreFactory->get('myclass.storename');
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('user.private_tempstore'),
$container->get('session_manager'),
$container->get('current_user')
);
}
Then you just need to ensure you start the session manager if the user is anonymous, before you need to put anything in the temp store:
if ($this->currentUser->isAnonymous() && !isset($_SESSION['session_started'])) {
$_SESSION['session_started'] = true;
$this->sessionManager->start();
}
You might find this approach preferable because it means that you can use a single system for temporary storage, regardless of whether a user is logged in.
(My code examples are lifted more-or-less verbatim from this excellent tutorial on building multi-step forms.)