Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class NovelRepository {
- // ...
- function getByIds(array $ids): NovelList
- {
- $record_cached = [];
- $cache_miss_ids = [];
- foreach($ids as $id) {
- // ดึงข้อมูลจาก cache มาก่อนใน ทุกไอดี ไม่มีไม่เป็นไรค่อยไปคิวรี่เอาทีหลัง
- $cached = $this->store->get("novel:$id", null);
- // ถ้ามีค่าจาก cache เก็บใส่คำตอบเอาไว้
- if ($cached !== null) {
- $record_cached[$id] = $cached;
- } else {
- // ถ้าใน id นั้นหาแคชไม่เจอ จับไอดีใส่ในอาเรย์ไว้ เพื่อเอาไปคิวรี่ where-in
- $cache_miss_ids[] = $id;
- }
- }
- if (!empty($cache_miss_ids)) {
- // keyby แปลง array เป็น key valued array ด้วยการเอาค่าจาก field ที่กำหนดเป็น key
- $queried_records = $this->model->whereIn('id', $cache_miss_ids)->get()->keyBy('id')->toArray();
- // ไล่เซฟข้อมูลลงแคช แยกตาม record
- foreach($queried_records as $id => $record) {
- $this->store->put("novel:$id", $record);
- }
- }
- // เราใช้คำตอบมี key ตาม ids ที่ใส่เข้ามา เพื่อให้คำตอบเราเรียงลำดับตาม $ids
- $result = array_fill_key($ids, null);
- // สำหรับแต่ละ id ที่เราใส่เข้ามา
- foreach($result as $id => $_) {
- // ถ้ามี record ไม่ว่าจาก cache หรือ query เอาไปแปลงเป็น Novel object แล้วค่อยยัดกลับใส่ array
- $record = $record_cached[$id] ?? $queried_records[$id] ?? null;
- $novel = $record === null ? null : $this->transformRecordToNovel($record);
- $result[$id] = $novel;
- }
- // คำตอบของเราต้องเป็น NovelList เลยหุ้มก่อนส่งออก
- return new NovelList(array_values($result));
- }
- }
Add Comment
Please, Sign In to add comment