Jump to content

Batching API Calls


goplutus

Recommended Posts

Is there a good way to batch API calls?

I'm building a service that requires  n^2 api calls for each city I add.  Naturally, this is getting a bit clunky (6 cities is 36 separate calls).  I lieu of finding a better webservice that can consolidate this into one API call, is there a good way to batch these so I don't get fatal errors when one of these fails?

 

Ideally, I'd be able to loop the calls until results are returned for each.

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/221351-batching-api-calls/
Share on other sites

interface MyBatchService
{
    public function someMethod();
}

class SomeService1 implements MyBatchService
{
    private $successor;
    
    public function __construct(MyBatchService $successor) {
        $this->successor = $successor;
    }
    
    public function someMethod() {
        if(!$this->canHandle()) {
            if($this->successor)
                return $this->successor->someMethod();
            throw new Exception('Failed to handle the request');
        }
    }
}

class SomeService2 implements MyBatchService
{
    private $successor;
    
    public function __construct(MyBatchService $successor) {
        $this->successor = $successor;
    }
    
    public function someMethod() {
        if(!$this->canHandle()) {
            if($this->successor)
                return $this->successor->someMethod();
            throw new Exception('Failed to handle the request');
        }
    }
}

class SomeService3 implements MyBatchService
{
    private $successor;
    
    public function __construct(MyBatchService $successor) {
        $this->successor = $successor;
    }
    
    public function someMethod() {
        if(!$this->canHandle()) {
            if($this->successor)
                return $this->successor->someMethod();
            throw new Exception('Failed to handle the request');
        }
    }
}

try {
    $batch = new SomeService1(new SomeService2(new SomeService3()));
    $batch->someMethod(); // initialize the chain
} catch(Exception $e) {
    echo $e->getMessage();
}

 

I assume each service returns the same information. The interface declares the common interface eg getUser(..) If a service fails to be able to handle the request (due to overload) it will try it's successor until the request is successfully handled or an exception is thrown.

Link to comment
https://forums.phpfreaks.com/topic/221351-batching-api-calls/#findComment-1146122
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.