Skip to content

Commit a22a8c0

Browse files
committed
Created cache class to handle caching results
1 parent 1ba10cb commit a22a8c0

File tree

2 files changed

+88
-1
lines changed

2 files changed

+88
-1
lines changed

src/Cache.php

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
<?php
2+
namespace hmerritt;
3+
4+
/**
5+
* Class Cache
6+
*
7+
*
8+
* @package hmerritt/imdb-api
9+
* @author Harry Merritt
10+
*/
11+
class Cache
12+
{
13+
14+
/**
15+
* Initiate cache database
16+
*
17+
* @var \Filebase\Database
18+
*/
19+
private $cache = new \Filebase\Database([
20+
'dir' => __DIR__ . DIRECTORY_SEPARATOR . 'cache/films/',
21+
'backupLocation' => __DIR__ . DIRECTORY_SEPARATOR . 'cache/films/backups/',
22+
'format' => \Filebase\Format\Json::class,
23+
'cache' => true,
24+
'cache_expires' => 31540000,
25+
'pretty' => false
26+
]);
27+
28+
/**
29+
* Add (or modify) an item in the cache
30+
*
31+
* @param string $key
32+
* @param string $value
33+
* @return bool
34+
*/
35+
public function add(string $key, $value)
36+
{
37+
$file = $this->get($key);
38+
$file->film = $value;
39+
$file->save();
40+
return true;
41+
}
42+
43+
/**
44+
* Counts all files in the cache
45+
*
46+
* @return int
47+
*/
48+
public function count(): int
49+
{
50+
return $this->$cache->count();
51+
}
52+
53+
/**
54+
* Deletes an item from the cache
55+
*
56+
* @return bool
57+
*/
58+
public function delete(string $key): bool
59+
{
60+
$file = $this->get($key);
61+
$file->delete();
62+
return true;
63+
}
64+
65+
/**
66+
* Check if an item exists in the cache
67+
*
68+
* @param string $key
69+
* @return bool
70+
*/
71+
public function exists(string $key): bool
72+
{
73+
return $this->$cache->has($key);
74+
}
75+
76+
/**
77+
* Get an item from the cache
78+
*
79+
* @param string $key
80+
* @return array
81+
*/
82+
public function get(string $key): array
83+
{
84+
return $this->$cache->get($key);
85+
}
86+
87+
}

tests/index.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
// Initialise Imdb
1515
// Load film data
1616
$imdb = new Imdb();
17-
$film = $imdb->search($q); // tt0816692 tt8633464
17+
$film = $imdb->film($q); // tt0816692 tt8633464
1818

1919
// Return loaded film data
2020
echo json_encode($film, JSON_PRETTY_PRINT);

0 commit comments

Comments
 (0)