svyatov/CurlWrapper

Bad to use the same class object for nested requests?

Closed this issue · 5 comments

This class has been great for working with an API that has quite a nested hierarchy (like the Shopify API) but I've experienced strange behaviours nesting one CurlWrapper object within nested loops of the results.

$shopify = new CurlWrapper();

$products = json_decode($shopify->get($products_url));
foreach ( $products as $product ):

    foreach ( $product->variants as $variant ):

        $metafields = json_decode($shopify->get($variant->url));
        foreach ( $metafields as $metafield ):
            $shopify->delete($metafield->url);
        endforeach;

    endforeach;

endforeach;

Obviously I've simplified my actual code for the example, but is there anything I should be doing as best-practice? I would've thought the class would reset itself after each request, but I ended up having to create multiple instances of the class to handle the request at each loop - is it bad to reuse the ($shopify in this case) same instance all the time? I also tried $shopify->reset() at the end of each loop, but this killed my auth and header settings (it's not supposed to according to src?)

Such a useful library tho- thanks!

What exactly "strange behaviours" do you experience?

I've managed to reproduce using this code- all works fine until the "product" loop begins a second time:

for ( $page = 1; $page <= $pages; $page++ )
{
    $products = json_decode($shopify->get($config['shopify']['url'] . 'products.json',array('page' => $page, 'limit'=>250 )));
    foreach ( $products->products as $product )
    {
        echo '[' . $product_count . '/' . $total_products . '] - ' . $product->title . chr(10);
        foreach ( $product->variants as $variant )
        {
            $data = $shopify->get($config['shopify']['url'] . 'variants/' . $variant->id . '/metafields.json');
            $metafields = json_decode($data);
            ......

The $product object is persisted as it should, but for every iteration after 250 products, the $data object is empty, which makes me think something is failing within the $shopify instance nested in the second foreach loop.

Hope this makes it clear enough

Example of output:

[249/1295] - Conditional Top - White Pixel
~~ metafields data returned ~~
[250/1295] - Conduct Jacket - Citron
~~ metafields data returned ~~
[251/1295] - Conduit Top - Diamond

[252/1295] - Conduit Top - Petrol Print

Ok, I'll try to figure out what is going on here this weekend, hopefully.

Can you provide me with some additional information?

  1. What is output of print_r($data);?
  2. What is output of print_r($shopify->getTransferInfo()); after executing $data = $shopify->get(...);
  3. Are any exceptions thrown? Maybe exceptions are catching silently somewhere in your code?