| 1 |
<?php |
| 2 |
namespace WPIDE\App\Services\Transient; |
| 3 |
|
| 4 |
use WPIDE\App\Services\Service; |
| 5 |
|
| 6 |
class Transient implements Service |
| 7 |
{ |
| 8 |
|
| 9 |
protected $prefix; |
| 10 |
|
| 11 |
public function init(array $config = []) |
| 12 |
{ |
| 13 |
|
| 14 |
$this->prefix = !empty($config['prefix']) ? $config['prefix'] : ''; |
| 15 |
} |
| 16 |
|
| 17 |
public function set($key, $val, $expiration = YEAR_IN_SECONDS) { |
| 18 |
|
| 19 |
return set_transient( $this->prefix.$key, $val, $expiration ); |
| 20 |
} |
| 21 |
|
| 22 |
public function get($key) { |
| 23 |
|
| 24 |
return get_transient( $this->prefix.$key ); |
| 25 |
} |
| 26 |
|
| 27 |
public function delete($key) { |
| 28 |
|
| 29 |
return delete_transient( $this->prefix.$key ); |
| 30 |
} |
| 31 |
|
| 32 |
public function exists($key) { |
| 33 |
|
| 34 |
return $this->get( $key ) !== false; |
| 35 |
} |
| 36 |
|
| 37 |
public function result($key, callable $callback, $expiration = YEAR_IN_SECONDS) { |
| 38 |
|
| 39 |
$cached = $this->get($key); |
| 40 |
|
| 41 |
if($cached === false || !empty($_GET['nocache'])) { |
| 42 |
|
| 43 |
$cached = $callback(); |
| 44 |
|
| 45 |
$this->set($key, $cached, $expiration); |
| 46 |
} |
| 47 |
|
| 48 |
return $cached; |
| 49 |
} |
| 50 |
|
| 51 |
} |