Cache always uses 1 hour duration?

I’m trying to save something in the cache using the Cache class so that I don’t accidentally send thousands of requests to the Twitch API.

For this, i have created the following code:

$config = Cache::engine("default");
$config->config("duration", "5 minutes");
Cache::config('twitch_channel_info', $config);

/* some other code that sends the request */

Cache::write('twitch_channel_info', ['my dope af data'],'twitch_channel_info');

It writes to the cache just fine, but the expiry date…
that’s 1 hour in the future, not 5 minutes.
How can I fix this issue?

https://book.cakephp.org/3.0/en/core-libraries/caching.html#configuring-cache-engines

You can also configure Cache engines at runtime:

Cache::config('short', [
   'className' => 'File',
   'duration' => '+1 hours',
   'path' => CACHE,
   'prefix' => 'cake_short_'
]);

so just

Cache::config('twitch_channel_info', ['duration' => '+5 minutes']);

should be enough, but if its always the same why not just set it in app.php from the start

Usually you configure cache engines as Graziel pointed out. But you might found bug here, where setting the duration in a human readable format later on isn’t converted into (int)seconds.

Using just this gives me an error:

The "twitch_channel_info" cache configuration does not exist

I have now specified it in the app.php and that does work:

'twitch_channel_info' => [
            'className' => 'File',
            'path' => CACHE,
            'serialize' => true,
            'duration' => '+5 minutes'
]

But I refrained from using app.php for this as that includes my sensitive data as well, so that doesn’t get committed… but I realised there was a app.default.php which I can modify as well for this.

app.default.php purpose is more that of an template. Of course it’s possible to read as many custom config files as you want, but if you worry about putting confidential credentials into them you should check out .env files: https://book.cakephp.org/3.0/en/development/configuration.html#environment-variables

There’s already a outcommented section at the top of config/bootstrap.php that gets you started.