13
13
class ProductRepository implements ProductContract
14
14
{
15
15
protected $ model ;
16
+ protected $ CACHE_KEY ;
16
17
17
18
public function __construct (Product $ model ){
18
19
$ this ->model = $ model ;
@@ -23,9 +24,38 @@ public function all(){
23
24
$ products = $ this ->model ->latest ()->get ();
24
25
return ProductResource::collection ($ products );
25
26
});
26
-
27
27
}
28
+ public function withFilter ($ request ){
29
+ // string $orderBy = 'id', string $sortBy = 'desc';
30
+ // {"page":"1","perPage":"10","orderBy":"created_at","sortBy":"desc"}
31
+ $ this ->SET_CACHE ($ request );
32
+ $ this ->flush ($ this ->CACHE_KEY );
33
+ $ KEY = $ this ->getCachekey ();
28
34
35
+ return Cache::remember ($ KEY , now ()->addMinutes (120 ), function () use ($ request ) {
36
+ $ products = $ this ->model ::filter ($ request );
37
+ return ProductResource::collection ($ products );
38
+ });
39
+ }
40
+ public function SET_CACHE ($ request )
41
+ {
42
+ $ page = $ request ->has ('page ' ) ? (int )$ request ->query ('page ' ) : 1 ;
43
+ $ perPage = $ request ->has ('perPage ' ) ? (int )$ request ->query ('perPage ' ) : 10 ;
44
+ $ orderBy = $ request ->has ('orderBy ' ) ? $ request ->query ('orderBy ' ) : 'created_at ' ;
45
+ $ sortBy = $ request ->has ('sortBy ' ) ? $ request ->query ('sortBy ' ) : 'desc ' ;
46
+ $ q = $ request ->has ('q ' ) ? $ request ->query ('q ' ) :"" ;
47
+ $ this ->CACHE_KEY = "products. $ page. $ perPage. $ orderBy. $ sortBy. $ q " ;
48
+ }
49
+ public function getCachekey ()
50
+ {
51
+ return $ this ->CACHE_KEY ;
52
+ }
53
+ public function flush ($ key )
54
+ {
55
+ if (cache ()->has ($ key )){
56
+ return cache ()->forget ($ key );
57
+ }
58
+ }
29
59
/**
30
60
* @param int $id
31
61
* @return mixed
@@ -37,6 +67,7 @@ public function all(){
37
67
* @return mixed
38
68
*/
39
69
public function create (array $ params ){
70
+ $ this ->flush ($ this ->CACHE_KEY );
40
71
$ product = $ this ->model ->create ($ params );
41
72
return new ProductResource ($ product );
42
73
}
@@ -59,6 +90,7 @@ public function update( $params,$id){
59
90
$ product = $ this ->findById ($ id );
60
91
if ($ product ){
61
92
$ updated = $ product ->update ($ params );
93
+ $ this ->flush ($ this ->CACHE_KEY );
62
94
return new ProductResource ($ product );
63
95
}
64
96
}
@@ -75,11 +107,15 @@ public function findById( $id){
75
107
*/
76
108
public function delete (int $ id ){
77
109
$ product = $ this ->findByCriteria ('id ' ,$ id );
78
- if ($ product ){ return $ product ->delete (); }
110
+ if ($ product ){
111
+ $ this ->flush ($ this ->CACHE_KEY );
112
+ return $ product ->delete ();
113
+ }
79
114
}
80
115
81
116
public function bulk_delete ($ selected_data )
82
117
{
118
+ $ this ->flush ($ this ->CACHE_KEY );
83
119
foreach ($ selected_data as $ product ) {
84
120
$ found = $ this ->findById ($ product ['id ' ]);
85
121
$ path = 'products/ ' .$ found ['image ' ];
0 commit comments