testing
[namibia] / module / Utility / src / Utility / Cache.php
1 <?php
2 namespace Utility;
3
4
5 /**
6  * Central cache functionality.
7  * @author andre.fourie
8  *
9  */
10 class Cache
11 {
12
13  /**
14   * @var \Memcache
15   */
16  static protected $cache = null;
17  /**
18   * @var boolean
19   */
20  static protected $cacheKick = true;
21  /**
22   * @var array
23   */
24  static private $loadedFromCache = array();
25
26
27
28  /**
29   * Store data in cache.
30   * @param string $key
31   * @param unknown $value
32   * @param integer $ttl
33   * @return boolean
34  */
35  static public function store($key, $value, $ttl = 0)
36  {
37   if (is_null(self::$cache))
38   {
39    self::$cache = new \Memcache();
40    self::$cache->pconnect('localhost', 11211);
41   }
42   return self::$cache->set($key, $value, 0, $ttl);
43  }
44
45  /**
46   * Fetch data from cache.
47   * @param string $key
48   * @param unknown $default
49   * @return unknown
50   */
51  static public function fetch($key, $default = false)
52  {
53   if (is_null(self::$cache))
54   {
55    self::$cache = new \Memcache();
56    self::$cache->pconnect('localhost', 11211);
57   }
58   $value = self::$cache->get($key);
59   return false !== $value
60    ? $value
61    : $default;
62
63  }
64
65  /**
66   * Delete cached item.
67   * @param string $key
68   */
69  static public function delete($key)
70  {
71   if (is_null(self::$cache))
72   {
73    self::$cache = new \Memcache();
74    self::$cache->pconnect('localhost', 11211);
75   }
76   self::$cache->delete($key);
77  }
78
79  /**
80   * Load a doctrine entity from cache. If not found in cache it will load from db and store in cache.
81   * @param string $entityName
82   * @param integer $id
83   * @param \Doctrine\ORM\EntityManager $em
84   * @param number $ttl
85   * @param number $depth
86   * @return unknown
87   */
88  static public function fetchEntity($entityName, $id, \Doctrine\ORM\EntityManager $em, $ttl = 300, $depth = 1)
89  {
90   if (isset(self::$loadedFromCache[$entityName . $id]))
91   {
92    $record =  $em->getRepository($entityName)->find($id);
93    return !is_null($record)
94     ? $record->toArray()
95     : null;
96   }
97   $cachedEntity = self::fetch($entityName . '::' . $id);
98   if (false !== $cachedEntity)
99   {
100    return $cachedEntity;
101   }
102
103   $entity = $em->getRepository($entityName)->find($id);
104   if (!is_null($entity))
105   {
106    $entity = $entity->toArray();
107    self::store($entityName . '::' . $id, $entity, $ttl);
108    self::$loadedFromCache[$entityName . $id] = true;
109   }
110   return $entity;
111  }
112
113 }
114