3

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.

2
  • Have you tried just using standard has, get and put methods?
    – SamV
    Dec 9, 2013 at 19:42
  • I have. Originally I was doing a simple test with those 3 methods but it had the same effect. I then realized I could simplify the process using the one method instead.
    – Aaron Frey
    Dec 10, 2013 at 16:16

1 Answer 1

3

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));
});
1
  • 1
    this helped me out. it appears that Cache::remember() cannot store an array. Sep 5, 2014 at 15:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.