|
| 1 | +Cache data in local files. |
| 2 | +========================== |
| 3 | + |
| 4 | +Short blurb. |
| 5 | + |
| 6 | +*** |
| 7 | + |
| 8 | +<a href="https://github.com/PhpGt/FileCache/actions" target="_blank"> |
| 9 | + <img src="https://badge.status.php.gt/filecache-build.svg" alt="Build status" /> |
| 10 | +</a> |
| 11 | +<a href="https://scrutinizer-ci.com/g/PhpGt/FileCache" target="_blank"> |
| 12 | + <img src="https://badge.status.php.gt/filecache-quality.svg" alt="Code quality" /> |
| 13 | +</a> |
| 14 | +<a href="https://scrutinizer-ci.com/g/PhpGt/FileCache" target="_blank"> |
| 15 | + <img src="https://badge.status.php.gt/filecache-coverage.svg" alt="Code coverage" /> |
| 16 | +</a> |
| 17 | +<a href="https://packagist.org/packages/PhpGt/FileCache" target="_blank"> |
| 18 | + <img src="https://badge.status.php.gt/filecache-version.svg" alt="Current version" /> |
| 19 | +</a> |
| 20 | +<a href="http://www.php.gt/filecache" target="_blank"> |
| 21 | + <img src="https://badge.status.php.gt/filecache-docs.svg" alt="PHP.Gt/FileCache documentation" /> |
| 22 | +</a> |
| 23 | + |
| 24 | +## Example usage: get the latitude/longitude of the user's IP address |
| 25 | + |
| 26 | +It's an expensive operation to make an HTTP call for every page view, but in this example we want to use a remote service to provide us with the estimated latitude/longitude of the current IP address. |
| 27 | + |
| 28 | +The first time we see the IP address will have to make an HTTP call, but subsequent calls will be able to take advantage of the cache. |
| 29 | + |
| 30 | +```php |
| 31 | +$ipAddress = $_SERVER["REMOTE_ADDR"]; |
| 32 | +$fileCache = new Gt\FileCache\Cache("/tmp/ip-address-geolocation"); |
| 33 | + |
| 34 | +// This function uses file_get_contents to contact the remote server |
| 35 | +// at ipinfo.io, a costly operation. We will pass the lookup function |
| 36 | +// into the cache, so it is only called when we don't have a fresh result. |
| 37 | +$lookup = function()use($ipAddress):string { |
| 38 | + $jsonString = file_get_contents("https://ipinfo.io/$ipAddress"); |
| 39 | + $obj = json_decode($jsonString); |
| 40 | + return $obj->loc; |
| 41 | +} |
| 42 | + |
| 43 | +$location = $fileCache->get("lat-lon", $lookup); |
| 44 | +echo "Your location is: $location"; |
| 45 | +``` |
0 commit comments