I am using Laravel 4 in conjunction with the a PHP Shopify connector. I am trying to limit the calls made to retrieve Shopify products by caching the particular product pages when they are first needed.
I made the following simple route in Laravel to test this flow:
Route::get('product/{id}', function($id)
{
$value = Cache::remember($id, 10, function() use ($id)
{
echo('Getting this from Shopify');
$shopify = new ShopifyLib;
return $shopify->getShopifyProduct($id);
});
var_dump($value);
});
ShopifyLib is a PHP library I wrote to communicate with the Shopify connector. The call returns a product page in JSON format correctly ever time. The problem is that the call is always being made externally to Shopify and not being retrieved from the cache.
I am using database caching with the following entry being saved:
key : laravel172989477
value : eyJpdiI6Imw4aUwzNHN4eExwdElPWFZKXC9hdFpVRjc4ZG5pK1dYMTlJVm44a1doKzlvPSIsInZhbHVlIjoieVJ6N2J6Q1A3SGNsWG1xWFJKTUdVak5FSEtHWDZKQkd2Y2x0ZEI2dHlvcz0iLCJtYWMiOiJhNWU0OGUxOTkyNWE2NTRhNTY1ZTNhMjRlOWNhNzRjNGI1ZDIyY2YzNGM3NTVjOThhMDUyYjllZmI1OTJiZmE1In0=
expiration : 1386616552
The $id never changes so I assume that this entry should be returned every time.
I tried a simpler example using:
Route::get('product/{id}', function($id)
{
$value = Cache::remember('test', 5, function()
{
echo('Not getting this from the cache!');
return 'example';
});
var_dump($value);
});
This worked as expected only calling the non-cache one time with all future calls going to the cache.
It turns out that the response coming back from Shopify was not actually JSON as I initially suspected. It was apparently an Array. By JSON encoding the response, the cache is working as expected.
Route::get('product/{id}', function($id)
{
$value = Cache::remember("product_$id", 10, function() use ($id)
{
echo('Getting this from Shopify');
$shopify = new ShopifyLib;
return json_encode($shopify->getShopifyProduct($id));
});
var_dump(json_decode($value));
});