Skip to content

Advanced Usage

Igor Sazonov edited this page Feb 4, 2026 · 1 revision

Advanced Usage

This section covers advanced topics and use cases for the Marketstack PHP SDK, including using the client without Laravel, debugging API requests, and implementing caching strategies.

Direct Client Usage (Without Laravel)

While the SDK is optimized for Laravel, it can be used in any PHP 8.1+ project. To do so, you can instantiate the MarketstackClient class directly:

use Tigusigalpa\Marketstack\MarketstackClient;

$client = new MarketstackClient(
    apiKey: 'your-api-key',
    baseUrl: 'http://api.marketstack.com/v1',
    timeout: 30
);

$data = $client->eod()
    ->symbols('AAPL')
    ->collect();

This provides the same fluent interface and functionality as the Laravel facade.

Debugging

If you need to inspect the full URL being generated for an API request, you can use the buildUrl() method. This is useful for debugging and ensuring that your parameters are being correctly formatted.

use Tigusigalpa\Marketstack\Facades\Marketstack;

$url = Marketstack::eod()
    ->symbols('AAPL')
    ->dateFrom('2023-01-01')
    ->buildUrl();

echo $url;
// Output: http://api.marketstack.com/v1/eod?access_key=xxx&symbols=AAPL&date_from=2023-01-01

Caching Strategies

To improve performance and avoid hitting API rate limits, it is highly recommended to cache API responses. Laravel's cache provides a simple and effective way to do this.

Here is an example of how to cache the results of an API call for 15 minutes:

use Illuminate\Support\Facades\Cache;
use Tigusigalpa\Marketstack\Facades\Marketstack;

$data = Cache::remember('aapl_eod_data', now()->addMinutes(15), function () {
    return Marketstack::eod()->symbols('AAPL')->collect();
});

This will store the results of the API call in the cache. Subsequent requests within the 15-minute window will be served from the cache, reducing latency and API usage.

Clone this wiki locally