所以我有一個方法可以生成快取鍵并自動應用瞬態。
這是方法:
private function get_cache($id, $count)
{
$cache_key = $this->generate_cache_key($id, $count);
return get_transient($cache_key);
}
我如何才能讓該方法回傳兩個$cache_key也get_transient?
這是我想要實作的目標:
- 在另一個方法中訪問 $cache_key。
- 呼叫方法時也要執行get_transient。
我有一個方法,這就是我要實作的目標:
public function delete_cache($count = 4)
{
$cache_key = $this->get_cache['cache_key'];
var_dump($cache_key);
}
所以我在想類似$instagram->get_cache['cache_key']但也保留原始功能的東西:
if ($cached = $instagram->get_cache($instagram->user_id, $count)) {
return $cached;
}
有誰知道我如何為另一種方法獲取 cache_key,但仍然保留 get_transient 回傳?
uj5u.com熱心網友回復:
從函式回傳多個值的概念稱為“元組”。幾乎每種語言都在某種程度上實作了這一點,有時作為“記錄”,有時作為“資料庫行”,或者作為結構。對于 PHP,您幾乎只能使用帶有欄位的物件或陣列,后者是最常見的。您的get_cache功能可以改寫為:
private function get_cache($id, $count)
{
$cache_key = $this->generate_cache_key($id, $count);
return [$cache_key, get_transient($cache_key)];
}
并呼叫它你會做:
[$cache_key, $value] = $this->get_cache('a', 4);
或者,如果使用舊版本的 PHP(或者您只是不喜歡它的外觀):
list($cache_key, $value) = $this->get_cache('a', 4);
這樣做的缺點是必須更改所有呼叫方以支持這一點,這可能是也可能不是問題。另一種方法是向執行更多作業的函式添加一個可選的回呼:
private function get_cache($id, $count, callable $func = null)
{
$cache_key = $this->generate_cache_key($id, $count);
$value = get_transient($cache_key);
if(is_callable($func)){
$func($cache_key, $value);
}
return $value;
}
并稱之為:
$value = $this->get_cache(
'a',
4,
static function($cache_key, $value) {
var_dump($cache_key);
}
);
盡管您使用的是 WordPress,但我認為了解其他框架的功能也會有所幫助。PSR-6定義了一個叫做CacheItemInterface回傳的物件形式的東西,Symfony 的快取(你實際上可以在 WordPress 中使用,我有時在大型專案中使用)使用 get-with-callback 語法。
uj5u.com熱心網友回復:
您可以回傳這兩個值的陣列
private function get_cache($id, $count)
{
$cache_key = $this->generate_cache_key($id, $count);
return [$cache_key, get_transient($cache_key)];
}
// ...
[$cache_key, $transient] = get_cache($id, $count);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/403878.html
標籤:
