如何使用PHP ArrayCachePool持久化缓存Token?
Got it, let's break down why your ArrayCachePool isn't holding onto the token across API calls, and how to fix this for good.
First, the core problem: ArrayCachePool is an in-memory only cache. That means all cached data lives only for the duration of a single PHP script execution. Once your API call finishes, PHP cleans up the memory allocated for the request—so your cached token is gone by the next request. Using a singleton won't help here because the singleton only exists within the current request's process.
Solution 1: Switch to a Persistent Cache Adapter
The most reliable fix is to use a cache adapter that persists data across requests. The php-cache ecosystem supports several options (filesystem, Redis, Memcached, etc.). Let's use the FilesystemAdapter as an example—it's easy to set up without extra services.
First, install the required package:
composer require cache/filesystem-adapter
Then, here's a complete implementation for your token caching logic (with 3-minute expiration):
use Cache\Adapter\Filesystem\FilesystemCachePool; use League\Flysystem\Local\LocalFilesystemAdapter; use League\Flysystem\Filesystem; // Initialize the filesystem cache pool (use a writable directory) $filesystemAdapter = new LocalFilesystemAdapter(__DIR__ . '/cache'); $filesystem = new Filesystem($filesystemAdapter); $pool = new FilesystemCachePool($filesystem); function getAuthToken($pool) { $tokenKey = 'global_auth_token'; $tokenItem = $pool->getItem($tokenKey); // Check if token is expired or doesn't exist if (!$tokenItem->isHit()) { // Call your authentication API to fetch a new token $newToken = fetchNewTokenFromAuthApi(); // Replace with your actual API call // Set token with 3-minute expiration (180 seconds) $tokenItem->set($newToken)->expiresAfter(180); $pool->save($tokenItem); return $newToken; } // Return the valid cached token return $tokenItem->get(); } // Usage in your API flow $token = getAuthToken($pool); // Use the token to call your business API callBusinessApi($token);
Solution 2: Session-Based Workaround (Not Recommended)
If you absolutely need to stick with an in-memory-style cache (not ideal for global tokens), you could use PHP sessions to persist the cache data. Note that sessions are user-specific, so this only works if the token is tied to individual users:
session_start(); // Initialize ArrayCachePool and load existing data from session $pool = new ArrayCachePool(); if (isset($_SESSION['cached_tokens'])) { $pool->setItems($_SESSION['cached_tokens']); } // Token retrieval logic $tokenKey = 'user_auth_token'; $tokenItem = $pool->getItem($tokenKey); if (!$tokenItem->isHit()) { $newToken = fetchNewTokenFromAuthApi(); $tokenItem->set($newToken)->expiresAfter(180); $pool->save($tokenItem); } $token = $tokenItem->get(); // Save cache data to session before the script ends $_SESSION['cached_tokens'] = $pool->getItems([$tokenKey]);
Key Takeaways
ArrayCachePoolis only useful for short-lived, per-request caching—never for data that needs to persist across requests.- For production environments, consider faster, scalable options like Redis or Memcached instead of the filesystem adapter.
- Ensure the cache directory (for FilesystemAdapter) is writable by your web server.
内容的提问来源于stack exchange,提问作者Suraj

