Skip to content

Commit 6a76138

Browse files
authored
docs: fix cache driver example
Current cache storage example is not working, because it assigns data to non existent variable. I have also added cookie persistence, because sessions only lasts for 20minutes. In most cases we would like to maintain cart items for at least a week.
1 parent cd30809 commit 6a76138

File tree

1 file changed

+32
-22
lines changed

1 file changed

+32
-22
lines changed

README.md

Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -986,43 +986,53 @@ class DBStorage {
986986
}
987987
```
988988

989-
For example you can also leverage Laravel's Caching (redis, memcached, file, dynamo, etc) using the below example,
989+
For example you can also leverage Laravel's Caching (redis, memcached, file, dynamo, etc) using the example below. Exmaple also includes cookie persistance, so that cart would be still available for 30 days. Sessions by default persists only 20 minutes.
990990

991991
```
992-
use Illuminate\Support\Facades\Cache;
992+
<?php
993993
994-
class CacheStorage {
994+
namespace App\Cart;
995995
996-
public function has($key)
997-
{
998-
return Cache::get($key);
999-
}
996+
use Carbon\Carbon;
997+
use Cookie;
998+
use Darryldecode\Cart\CartCollection;
1000999
1001-
public function get($key)
1000+
class CacheStorage
10021001
{
1003-
if($this->has($key))
1002+
private $data = [];
1003+
private $cart_id;
1004+
1005+
public function __construct()
10041006
{
1005-
return new CartCollection(Cache::get($key));
1007+
$this->cart_id = \Cookie::get('cart');
1008+
if ($this->cart_id) {
1009+
$this->data = \Cache::get('cart_' . $this->cart_id, []);
1010+
} else {
1011+
$this->cart_id = uniqid();
1012+
}
10061013
}
1007-
else
1014+
1015+
public function has($key)
10081016
{
1009-
return [];
1017+
return isset($this->data[$key]);
10101018
}
1011-
}
10121019
1013-
public function put($key, $value)
1014-
{
1015-
if($row = Cache::get($key))
1020+
public function get($key)
10161021
{
1017-
// update
1018-
$row->cart_data = $value;
1019-
Cache::put($key, $value, now()->addMinutes(3600));
1022+
return new CartCollection($this->data[$key] ?? []);
10201023
}
1021-
else
1024+
1025+
public function put($key, $value)
10221026
{
1023-
Cache::put($key, $value, now()->addMinutes(3600));
1027+
$this->data[$key] = $value;
1028+
\Cache::put('cart_' . $this->cart_id, $this->data, Carbon::now()->addDays(30));
1029+
1030+
if (!Cookie::hasQueued('cart')) {
1031+
Cookie::queue(
1032+
Cookie::make('cart', $this->cart_id, 60 * 24 * 30)
1033+
);
1034+
}
10241035
}
1025-
}
10261036
}
10271037
```
10281038

0 commit comments

Comments
 (0)