Search code examples
phpcachingaws-secrets-managerfat-free-framework

F3 Framework: how to make sure that caching is working correctly?


I'm getting the database credentials from AWS secrets manager and storing it in the cache so that it doesn't have to be fetched from AWS on every request.

The problem is that, if I change the secret name for testing, F3 won't be able to connect to the database. That means that it's detecting the secret name getting changed even though I tell F3 to check that only if it wasn't able to find anything cached.

use Aws\SecretsManager\SecretsManagerClient;

$f3->set('CACHE', true);

if ($f3->exists('dbusername')) {
    $username = $f3->get('dbusername');
    $password = $f3->get('dbpassword');
    $host = $f3->get('dbhost');
    $port = $f3->get('dbport');
} else {
    $secretName = getenv('AWS_SECRET_NAME');
    $client = new SecretsManagerClient([
        'version' => 'latest'
    ]);

    $secretManager = $client->getSecretValue([
        'SecretId' => $secretName,
    ]);

    $db = json_decode($secretManager['SecretString']);
    $username = $db->username;
    $password = $db->password;
    $port = $db->port;
    $host = $db->host;
}
    $f3->set('dbusername', $username);
    $f3->set('dbpassword', $password);
    $f3->set('dbhost', $host);
    $f3->set('dbport', $port);

I'm testing on my PC, I don't know if that code would work on a server, not sure if the issue from my PC or if I'm not caching correctly.


Solution

  • It turns out that the cache wouldn't work unless a ttl (time to live) is specified. Here's how to cache the values above for 24 hours.

    $f3->set('dbusername', $username, 86400);
    $f3->set('dbpassword', $password, 86400);
    $f3->set('dbhost', $host, 86400);
    $f3->set('dbport', $port, 86400);