Guest User

Untitled

a guest
Feb 18th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. <?php
  2.  
  3. class NovelRepository {
  4.  
  5. // ...
  6.  
  7. function getByIds(array $ids): NovelList
  8. {
  9. $record_cached = [];
  10. $cache_miss_ids = [];
  11.  
  12. foreach($ids as $id) {
  13.  
  14. // ดึงข้อมูลจาก cache มาก่อนใน ทุกไอดี ไม่มีไม่เป็นไรค่อยไปคิวรี่เอาทีหลัง
  15. $cached = $this->store->get("novel:$id", null);
  16.  
  17. // ถ้ามีค่าจาก cache เก็บใส่คำตอบเอาไว้
  18. if ($cached !== null) {
  19. $record_cached[$id] = $cached;
  20. } else {
  21. // ถ้าใน id นั้นหาแคชไม่เจอ จับไอดีใส่ในอาเรย์ไว้ เพื่อเอาไปคิวรี่ where-in
  22. $cache_miss_ids[] = $id;
  23. }
  24.  
  25. }
  26.  
  27. if (!empty($cache_miss_ids)) {
  28. // keyby แปลง array เป็น key valued array ด้วยการเอาค่าจาก field ที่กำหนดเป็น key
  29. $queried_records = $this->model->whereIn('id', $cache_miss_ids)->get()->keyBy('id')->toArray();
  30.  
  31. // ไล่เซฟข้อมูลลงแคช แยกตาม record
  32. foreach($queried_records as $id => $record) {
  33. $this->store->put("novel:$id", $record);
  34. }
  35. }
  36.  
  37. // เราใช้คำตอบมี key ตาม ids ที่ใส่เข้ามา เพื่อให้คำตอบเราเรียงลำดับตาม $ids
  38. $result = array_fill_key($ids, null);
  39.  
  40. // สำหรับแต่ละ id ที่เราใส่เข้ามา
  41. foreach($result as $id => $_) {
  42. // ถ้ามี record ไม่ว่าจาก cache หรือ query เอาไปแปลงเป็น Novel object แล้วค่อยยัดกลับใส่ array
  43. $record = $record_cached[$id] ?? $queried_records[$id] ?? null;
  44. $novel = $record === null ? null : $this->transformRecordToNovel($record);
  45. $result[$id] = $novel;
  46. }
  47.  
  48. // คำตอบของเราต้องเป็น NovelList เลยหุ้มก่อนส่งออก
  49. return new NovelList(array_values($result));
  50. }
  51.  
  52. }
Add Comment
Please, Sign In to add comment