This is not really Phalcon related but here it goes anyway.
This shows a simple example of using the queue to generate a response.
Your API endpoint only creates a job in the queue and can return immediately.
When the item is picked from the queue the request to the external API is made and when a reponse is recieved it calls the callback supplied by the original callee.
This example could be improved by splitting the job in two, one job for external api retrieval and a seperate job for the callback. This way the extarnal Api isn't called agian when the callback fails. This also allows for multiple callback attempts by keeping a counter for failed deliveries.
ApiController
public function myApiEndpointAction($myArgument, $callbackUrl) {
$queue->put(array(
'jobName' => $myArgument,
'callbackUrl' => $callbackUrl
));
return new Reponse("Item put in queue", 201);
}
Worker
while (($job = $queue->peekReady()) !== false) {
$jobBody = $job->getBody();
if(isset($jobBody['jobName']) {
$myArgument = $jobBody['jobName'];
$callbackUrl = $jobBody['callbackUrl'];
//Call external API
$external = curl_init();
curl_setopt_array($external, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'https://external.api.com'
));
//The reponse from the external API
$result = curl_exec($external);
if(!$result) {
//External api failed
//Don't delete job, will be pickedup again the next round
curl_close($external);
return;
}
curl_close($external);
//Return the response to the original callee
$callback = curl_init();
curl_setopt_array($callback, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $callbackUrl, //The url which the original api caller gave
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => array(
data => $result //The response from the external api call
)
));
$deliverd = curl_exec($callback);
if(!$deliverd) {
curl_close($callback);
return;
}
curl_close($callback);
}
//Remove the job from the queue
$job->delete();
}