So I have a single method that generated a cache key and also applies a transient automatically.
Here is the method:
private function get_cache($id, $count)
{
$cache_key = $this->generate_cache_key($id, $count);
return get_transient($cache_key);
}
How could I make that method return both the $cache_key
but also get_transient
?
Here is what I’m trying to achieve:
- Access the $cache_key inside another method.
- Also execute the get_transient when calling the method.
I have a method and this is what I’m aiming to achieve:
public function delete_cache($count = 4)
{
$cache_key = $this->get_cache['cache_key'];
var_dump($cache_key);
}
So I was thinking something like $instagram->get_cache['cache_key']
but also keep the original functionality for:
if ($cached = $instagram->get_cache($instagram->user_id, $count)) {
return $cached;
}
Does anyone know how I can get the cache_key for another method, but still keep the get_transient return?
2
Answers
You could return an array of those two values
The concept of returning multiple values from a function is called a "tuple". Almost every language implements this to some degree, sometimes as a "record", sometimes as a "database row", or maybe as a struct. For PHP, you are pretty much limited to either an object with fields, or an array, with the latter being the most common. Your
get_cache
function could be reworked as:And to invoke it you’d do:
Or, if using an older version of PHP (or you just don’t like the look of that):
The downside of this is that all callers have to be changed to support this, which may or may not be a problem. An alternative is to add an optional callback to the function that performs more work:
And call it like:
Although you are using WordPress, I think it is helpful to see what other frameworks do, too. PSR-6 defines something called
CacheItemInterface
which is the object-form of the return, and Symfony’s cache (which you can actually use in WordPress, I do sometimes on large projects) uses the get-with-callback syntax.