1. Go to this page and download the library: Download maciej-sz/nbp-php library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
use Symfony\Component\Cache\Adapter\FilesystemAdapter as CachePoolAdapter;
// 1) create repository backed by caching transport
$cachePool = new CachePoolAdapter();
$cachingTransportFactory = CachingTransportFactory::new($cachePool);
$client = NbpWebClient::new(transportFactory: $cachingTransportFactory);
$nbpRepository = NbpWebRepository::new($client);
// 2) create needed services using cache-backed repository:
$goldRates = new GoldRatesService($nbpRepository);
// 3) run multiple times to check the effect of caching:
$start = microtime(true);
$goldRates->fromDayBefore('2013-05-15')->getValue();
$end = microtime(true);
$took = $end - $start;
printf('Getting the rate took %F ms', $took * 1000);
$customTransportFactory = new class() implements TransportFactory {
public function create(string $baseUri): Transport
{
return new class() implements Transport {
public function get(string $path): array
{
echo "Requesting resource: {$path}" . PHP_EOL;
$ch = curl_init();
$url = NbpWebClient::BASE_URL . $path;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
try {
$output = curl_exec($ch);
} finally {
curl_close($ch);
}
echo 'Request successful' . PHP_EOL;
return json_decode($output, true);
}
};
}
};
$client = NbpWebClient::new(transportFactory: $customTransportFactory);
$nbpRepository = NbpWebRepository::new($client);
$goldRates = GoldRatesService::new($nbpRepository);
$rate = $goldRates->fromDay('2022-01-03');
printf(
'Gold rate from %s is %F',
$rate->getDate()->format('Y-m-d'),
$rate->getValue()
);
bash
composer
Requesting resource: /api/cenyzlota/2022-01-01/2022-01-31
Request successful
Gold rate from 2022-01-03 is 235.720000
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.