Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@sscovil
Created July 9, 2019 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sscovil/2ce9168de6d5223a9d8b11da9b205dda to your computer and use it in GitHub Desktop.
Save sscovil/2ce9168de6d5223a9d8b11da9b205dda to your computer and use it in GitHub Desktop.
<?php
class API {
public static function fetchUser($userID) {
static $cache = [];
$url = "https://example.com/users";
$method = "GET";
if (isset($cache[$url][$method][$userID])) {
print "Using cached value";
return $cache[$url][$method][$userID];
}
print "No cached value, fetching from API";
$user = array("id" => $userID, "name" => "User $userID"); // Replace this with the actual API call
$cache[$url][$method][$userID] = $user;
return $user;
}
}
$user1 = API::fetchUser(1);
print "\n" . json_encode($user1, JSON_PRETTY_PRINT) . "\n";
$user2 = API::fetchUser(2);
print "\n" . json_encode($user2, JSON_PRETTY_PRINT) . "\n";
$user1 = API::fetchUser(1);
print "\n" . json_encode($user1, JSON_PRETTY_PRINT) . "\n";
@sscovil
Copy link
Author

sscovil commented Jul 9, 2019

This is an example of a simple in-memory cache using a function-scoped static variable to prevent making duplicate API calls on the same request.

Output:

$ php simple-cache-example.php 
No cached value, fetching from API
{
    "id": 1,
    "name": "User 1"
}
No cached value, fetching from API
{
    "id": 2,
    "name": "User 2"
}
Using cached value
{
    "id": 1,
    "name": "User 1"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment