Created
July 9, 2019 14:15
-
-
Save sscovil/2ce9168de6d5223a9d8b11da9b205dda to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: