我正在嘗試將快取添加到現有的 Symfony 專案中。但我不確定如何最好地進行我得到一個帶有 id 的陣列。如果快取中有專案,我會檢查每個 id。如果沒有,則中斷并向資料庫發送查詢。然后我會得到結果,現在我可以將這些值存盤在我的快取中。但我不知道如何將 id 設定為鍵
public function getHelpfulResult(array $reviewIds): array
{
$helpfulCache = new FilesystemAdapter("helpful", 2 * 60 * 60, "cache");
$helpfulValues = [];
foreach ($reviewIds[0] as $id) {
$item = $helpfulCache->getItem((string)$id);
if($item->isHit()) {
array_push($helpfulValues, $item);
} else {
break;
}
}
$repo = $this->getDoctrine()->getRepository('Project:Test\Helpful', 'reviews');
$query = $repo->createQueryBuilder('helpful')
->where("helpful.parentId IN (:parentIds) AND helpful.type = 'review'")
->setParameter('parentIds', $reviewIds)
->getQuery();
$result = $query->getResult();
foreach($result as $item) {
$cache->set($item);
}
$cache->save();
return $result;
}
uj5u.com熱心網友回復:
關于基本:“我如何為快取項設定'id'”問題:
你基本上不會。您嘗試通過 ID 檢索快取項,然后您已經擁有該 ID 的物件是否命中。
您保存它,現在存在一個 ID 為“x”的新快取項。
例如
$cacheItem = $cacheyAdapter->getItem('some-arbitrary-id');
if (!$cacheItem->isHit()) {
$cacheItem->set('some new value');
$cacheAdapter->save($cacheItem);
}
使用上面的代碼,您將檢查some-arbitrary-id快取層中是否存在,以及它是否沒有為其設定值并將其存盤回來。
關于問題中的其余代碼,恐怕整個事情設計得相當糟糕,快取中的一個元素已經過時,迫使您再次進行整個查詢并從資料庫中檢索所有內容。
我不會花時間在這個問題上,因為它超出了這個問題的范圍(而且對于 SO 來說太寬泛和固執己見),一些基本的想法:
- 序列化整個查詢和快取的結果是
- 從第二個查詢中排除您在快取中命中的 id(從陣列中洗掉它們
$reviewIds)。此外,將未命中的快取項保存在另一個陣列中,這樣當您從資料庫中獲取它們時,您可以更新快取層中的那些。最后在回傳之前合并快取和資料庫中的結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/406904.html
標籤:
