NATS4 API nusoap wsdlcache

From TMM Wiki
Revision as of 00:03, 3 February 2016 by TMMNick (talk | contribs)
Jump to navigationJump to search

When using the SOAP API, you can improve performance by caching the NATS wsdl file. This article shows an example of using the "nusoap_wsdlcache" to do so.

To use the "nusoap_wsdlcache" class, be sure to include it at the top of your script making the API calls. The "nusoap_wsdlcache" takes 2 parameters when declaring a new instance:

  • Directory where cache files will be stored (<cache_dir> in example below)
  • The time limit of the cache file in seconds (<wsdl_cache_lifetime> in example below)

If you are using the TMM library version of nusoap, the wsdlcache class may already be included. This example shows how to check for the class before including the individual class file to prevent double inclusion.

The first time you make an API call using the nusoap wsdlcache, there will still be a request for the wsdl file to start the cache. Once the cache file is created, subsequent API calls will load the wsdl from the cache file rather than trying to request it. You can manually clear the cache by going into your <cache_dir> and removing the wsdlcache-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX, and wsdlcache-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.lock file created for the NATS API wsdl.

<?

/* Exmple API call using nusoap_wsdlcache class */
/* nusoap includes */
require_once('nusoap/lib/nusoap.php');
if(!class_exists("nusoap_wsdlcache")){ 
	require_once('nusoap/lib/class.wsdlcache.php');
}

//API login vars
$username = '<admin_username>'; // your admin username
$apikey = '<api_key>'; // your api key
$url = 'http://<your_nats_domain>/admin_api.php?wsdl'; // change <your_nats_domain>  to be domain of your NATS install

/* Nusoap WSDL cache setup */
//cache vars
$cache_dir = "<cache_dir>"; // change <cache_dir> to be the directory for storing cache files
$wsdl_cache_lifetime = <wsdl_cache_lifetime>; // change  <wsdl_cache_lifetime> to an amount in seconds

//construct cache
$wsdlCache = new nusoap_wsdlcache($cache_dir, $wsdl_cache_lifetime);

//try to get cache
$wsdl = $wsdlCache->get($url);
if (is_null($wsdl)) {
	//cache file not found, need to create new one
	$wsdl = new wsdl();
	$wsdl->setCredentials($username,$apikey);// need to login for NATS wsdl 
	$wsdl->fetchWSDL($url); //get the wsdl
	$wsdlCache->put($wsdl); //create cache file
}
$client = new nusoap_client($wsdl, TRUE);
/* end Nusoap WSDL cache setup */

//set your login for the soap client
$client->setCredentials($username,$apikey);

// Check for an error
$err = $client->getError();
if ($err) {
    // Display the error
    echo 'Constructor error' . $err . "\n";
    exit; // At this point, you know the call that follows will fail
    
}

//make an API call
$result = $client->call('ping', Array(), 'natsapiadmin_wsdl');
var_dump($result);