Advertisement
Guest User

AndrewCarterUK - PSR-6 getExpiration() solution

a guest
Feb 4th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.48 KB | None | 0 0
  1. <?php
  2.  
  3. class Item
  4. {
  5.     private $key;
  6.     private $expirations;
  7.  
  8.     public function __construct($key, ArrayObject $expirations)
  9.     {
  10.         $this->key = $key;
  11.         $this->expirations = $expirations;
  12.     }
  13.  
  14.     public function __destruct()
  15.     {
  16.         if (isset($this->expirations[$this->key])) {
  17.             unset($this->expirations[$this->key]);
  18.         }
  19.     }
  20.  
  21.     public function getKey()
  22.     {
  23.         return $this->key;
  24.     }
  25.  
  26.     public function setExpiration($expiration)
  27.     {
  28.         $this->expirations[$this->key] = $expiration;
  29.     }
  30. }
  31.  
  32. class Pool
  33. {
  34.     private $expirations;
  35.  
  36.     public function __construct()
  37.     {
  38.         $this->expirations = new ArrayObject();
  39.     }
  40.  
  41.     public function getItem($key)
  42.     {
  43.         return new Item($key, $this->expirations);
  44.     }
  45.  
  46.     public function save(Item $item)
  47.     {
  48.         $key = $item->getKey();
  49.  
  50.         if (isset($this->expirations[$key])) {
  51.             echo 'Item ' . $key . ' expires at: ' . $this->expirations[$key] . PHP_EOL;
  52.         } else {
  53.             echo 'Item ' . $key . ' expiry not set' . PHP_EOL;
  54.         }
  55.     }
  56. }
  57.  
  58. // Test it works
  59.  
  60. $pool = new Pool();
  61.  
  62. $foo = $pool->getItem('foo');
  63. $bar = $pool->getItem('bar');
  64.  
  65. $foo->setExpiration(100);
  66.  
  67. $pool->save($foo); // Item foo expires at 100
  68. $pool->save($bar); // Item bar expiry not set
  69.  
  70. // Check for protection against memory leak
  71. $foo2 = clone $foo;
  72. unset($foo);
  73. $pool->save($foo2); // Item foo expiry not set
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement