Third-party external calls

Class Lib\DataSync

Introduction

This class is useful for calling an external API or url to your project.
The class uses CURL to make the call.
It allows you to specify the type of format you want (json, xml, plain-text, ...).

The advantage of using this class instead of making a CURL call directly in your webservice is twofold:

  • this class allows to retrieve a set of metrics useful for monitoring the application (number of external calls sent, execution times, response times ...)
  • this class allows you to set cache on a GET call in order to gain performance.

We therefore recommend that you always use this class for any third-party calls.

📘

Note

The cached information is stored in Redis, which ensures good read performance.

Methods

__construct

<?php public function __construct(string $format = "plain-text", array $confds = null)

Description
Instantiates a Datasync object

Parameters

  • format
    Output Format (xml, json, plain-text, ...)
  • confds
    Array
    Table containing information useful for caching call return :
<?php
$confds = array(
  'NameOfMethod' => array(
    'cache' => true, // true or false
    'ttl' => 3600, // Time to live the cache in seconds
  )
);

call

<?php public function call(string $url, string $method = null, bool $forcenocache = false)

Description
Create a new cURL resource, set URL and other appropriate options and perform a cURL session.

Parameters

  • url Url to call
  • method Méthod used
  • forcenocache Boolean to force the use of the cache or not. (default = false)

Return
Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.


Examples

Make a call to an external api with cache of 1 hour

At first call, the method will cache the curl result in Redis with a 1 hour of time to live (3600 seconds).
The following calls will retrieve the data in Redis if they exist to return them faster.

<?php

$conf = \Lib\Config::getConf();
$apiurl = $conf['api']['apiurl'];

$confds = array(
    'getDatas' => array(
        'cache' => true,
        'ttl' => 3600,
    )
);

$ds = new \Lib\DataSync('json', $confds);

$headers = array();
$headers[] = "Content-Type: multipart/form-data";

curl_setopt($ds->curl, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ds->curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ds->curl, CURLOPT_HTTPHEADER, $headers);

$response = $ds->call($apiurl,'getDatas');

if (!empty($response['error'])) {
    return \Lib\Tools::info($response['error']['message'], true, false, 3);
}

return $response;