Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [klasa, PHP5, SimpleXML] Cache
Forum PHP.pl > Forum > Gotowe rozwiązania > Algorytmy, klasy, funkcje
Neotion
... i ich późniejszgo odzyskiwania

Działa w oparciu o bazowaną na XML prezentację zmiennych.

Funkcje:<br>
* zapis-odczyt nast. tpyów danych: array (wielowymiarowe również), string, float, boolean, integer
* obsługa plików jak i możliwość działania bez ich uzycia (stringi XML, do dopracowania (działa tylko odczyt stringów))
* Usługa czasowej kontroli ważności cache'u (podajesz przez jaki czas cache jest ważny i potem zmienna isValid przyjmuje odpowiednią wartość)

TODO: przerobienie niektórych metod tak aby pasowały do modelu MVC (w szczególności metody save() )

Póki co klasa działa ok, jeżeli chodzi o wykorzystanie klasy z użyciem wbudowanej obsługi plików.

Kod:
  1. <?php
  2.  
  3. /**
  4.  * Cache management API
  5.  * Used for storing variables
  6.  * 
  7.  * @author Artek Wiśniewski <aart3k@gmail.com>
  8.  * @version $Id: cache.class.php,v 0.7.5 2006/04/12 22:31:48 aart3k Exp $
  9.  * @package nsAPI
  10.  * @todo Cache rebuilds, MVC compatibility
  11.  */
  12.  
  13. define(CACHE_DEFAULT_DIR,'cache/');
  14.  
  15. class Cache{
  16.  
  17. /**
  18.  * Stores the reference to SimpleXMLElement
  19.  *
  20.  * @var object
  21.  */
  22. private $XMLElement;
  23.  
  24. /**
  25.  * XML-formatted variables (obtained/current)
  26.  *
  27.  * @var string
  28.  */
  29. public $XML;
  30.  
  31. /**
  32.  * Stores the cache-file path
  33.  *
  34.  * @var string
  35.  */
  36. public $file;
  37.  
  38. /**
  39.  * Array that contains obtained grom cache variables
  40.  *
  41.  * @var array
  42.  */
  43. public $variables;
  44.  
  45. /**
  46.  * True if cache is still valid
  47.  *
  48.  * @var bool
  49.  */
  50. public $isValid;
  51.  
  52. /**
  53.  * Number of seconds for which cache is valid
  54.  *
  55.  * @var int
  56.  */
  57. public $expires;
  58.  
  59. /**
  60.  * Loader of Cache
  61.  * Loads stored cache (if there is one) and initializes parsing
  62.  *
  63.  * @param string $name
  64.  * @param int $expires
  65.  * @param string $validType days|hours|minutes|seconds (default)
  66.  * @param string $XMLdata Ready XML-ed variables (this var has higher prority)
  67.  */
  68. public function __construct($name,$expires,$expiresUnit = NULL,$XMLdata = NULL){
  69.  
  70. $this->file = CACHE_DEFAULT_DIR.md5($name).'.che.php';
  71.  
  72. $this->expires = $expires;
  73. if($validType == 'minutes')
  74. $this->expires = 60 * $this->expires;
  75. if($validType == 'hours')
  76. $this->expires = 3600 * $this->expires;
  77. if($validType == 'days')
  78. $this->expires = 86400 * $this->expires;
  79.  
  80. /* Get saved cache if exists or use gived XML-data in param */
  81. if($XMLdata)
  82. $this->XML = $XMLdata;
  83.  
  84. else {
  85.  
  86. if(!file_exists($this->file)){
  87. file_put_contents($this->file,'<?php $cache=<<<XML
  88. <?xml version="1.0"?>
  89. <nscache>
  90. <validto type="unix">0</validto>
  91. <cacheid>'.uniqid().'</cacheid>
  92. <name>'.$name.'</name>
  93. <rebuilt file="" function="" />
  94. <variables>
  95. <empty />
  96. </variables>
  97. </nscache>
  98. XML;
  99. ?>');// REBUILTS for implement!
  100. }
  101. include($this->file);
  102. $this->XML = $cache;
  103.  
  104. }
  105.  
  106. $this->refresh();
  107.  
  108. }
  109.  
  110. /**
  111.  * Gets the current value of $this->XML variable and parses its data to variables
  112.  * Use when XML var was changed externally
  113.  * 
  114.  */
  115. public function refresh(){
  116.  
  117. $this->XMLElement = new SimpleXMLElement($this->XML);
  118.  
  119. foreach ($this->XMLElement->variables->variable as $variable)
  120. $this->variables[(string) $variable['name']] = $this->parseVariableXML($variable);
  121.  
  122. if((int) $this->XMLElement->validto > time())
  123. $this->isValid = true;
  124. else 
  125. $this->isValid = false;
  126.  
  127. }
  128.  
  129. /**
  130.  * Saves last obtained / refreshed / putted vars
  131.  * with new uniqid and time() signature
  132.  *
  133.  */
  134. public function save(){
  135.  
  136. foreach ($this->variables as $name => $value)
  137. $dump .= $this->parseVariable($name,$value);
  138.  
  139. $this->XML = ereg_replace('<variables>.*</variables>','<variables>
  140. '.$dump.'</variables>',$this->XML);
  141.  
  142. $this->XMLElement = new SimpleXMLElement($this->XML);
  143.  
  144. $this->XMLElement->validto = time() + $this->expires;
  145. $this->XMLElement->cacheid = uniqid();
  146.  
  147. file_put_contents($this->file,'<?php $cache=<<<XML
  148. '.$this->XMLElement->asXML().'
  149. XML;
  150. ?>');
  151.  
  152. $this->isValid = true;
  153.  
  154. }
  155.  
  156. /**
  157.  * Stores the variable in current cache (does not save the file)
  158.  * 
  159.  * @param string $var1Name
  160.  * @param mixed $var1Value
  161.  * @param string $var2Name
  162.  * @param mixed $var2Value
  163.  * ...
  164.  * @param string $varnName
  165.  * @param mixed $varnValue
  166.  */
  167. public function store(){
  168. $params = func_get_args();
  169. $dump = '';
  170.  
  171. while (list($key,$value) = each($params)) {
  172. if($key % 2 != 0)
  173. $this->variables[$name] = $value;
  174. else
  175. $name = $value;
  176. }
  177.  
  178. }
  179.  
  180. /**
  181.  * Returns array with last obtained variables
  182.  *
  183.  * @return array
  184.  */
  185. public function getCachedVars(){
  186.  
  187. return $this->variables;
  188.  
  189. }
  190.  
  191. /**
  192.  * Used to extract variable from XML-obtained data
  193.  *
  194.  * @param XSimpleXMLElement Object $variable
  195.  * @return mixed
  196.  */
  197. private function parseVariableXML($variable){
  198.  
  199. switch ((string) $variable['type']) {
  200. case 'array':
  201. foreach ($variable->children() as $children){
  202. $parsedVar[(string) $children['name']] = $this->parseVariableXML($children);
  203. }
  204. break;
  205.  
  206. case 'string':
  207. $parsedVar = utf8_decode($variable);
  208. break;
  209.  
  210. case 'boolean':
  211. $parsedVar = (bool) (string) $variable;
  212. break;
  213.  
  214. case 'float' OR 'double' OR 'single':
  215. $parsedVar = floatval((string) $variable);
  216. break;
  217.  
  218. case 'integer':
  219. $parsedVar = (int) (string) $variable;
  220. break;
  221.  
  222. default:
  223. $parsedVar = utf8_decode($variable);
  224. break;
  225.  
  226. }
  227.  
  228. return $parsedVar;
  229.  
  230. }
  231.  
  232. /**
  233.  * Makes the variable XML-dump (not complete XML, only this var tag)
  234.  *
  235.  * @param string $name Name of variable
  236.  * @param mixed $value Variable itself
  237.  * @return string Dump
  238.  */
  239. private function parseVariable($name,$value){
  240. $type = gettype($value);
  241.  
  242. if($type == 'array'){
  243.  
  244. $arrayDump = '<variable name="'.$name.'" type="array">
  245. ';
  246. foreach ($value as $key => $var)
  247. $arrayDump .= $this->parseVariable($key,$var);
  248.  
  249. $arrayDump .= '</variable>
  250. ';
  251.  
  252. }else 
  253. $arrayDump = utf8_encode('<variable name="'.$name.'" type="'.$type.'"><![CDATA['.(string) $value.']]></variable>');
  254.  
  255. return $arrayDump;
  256.  
  257.  
  258. }
  259.  
  260. }
  261.  
  262. ?>


Przykłady będą oparte o nast. zmienne:
  1. <?php
  2.  
  3. $putFloat = 4124.3242355;
  4. $putString = "aktualśśśśny</a></b>";
  5. $putBoolean = false;
  6. $putInteger = 3254235;
  7. $putArray[0] = "element zerowy";
  8. $putArray[1][0] = "element 1 :: podelement 0";
  9. $putArray[1][1] = 2144321.213421;
  10.  
  11. ?>


Na końcu każdego dam var_dump() dla pokazania że zadziałało smile.gif
Dobrze jest wykonywać przykłady po kolei...

Przykład 1: Zapis
  1. <?php
  2.  
  3. $new = new Cache('testCache',50);
  4.  
  5. $new->variables['putFloat'] = $putFloat;
  6. $new->variables['putString'] = $putString;
  7. $new->variables['putBoolean'] = $putBoolean;
  8. $new->variables['putArray'] = $putArray;
  9.  
  10. $new->save();
  11.  
  12. var_dump($new->variables);
  13.  
  14. ?>


Przykład 2: Odczyt
  1. <?php
  2.  
  3. $new = new Cache('testCache',50);
  4.  
  5. /*
  6. $new->variables['putFloat'] = $putFloat;
  7. $new->variables['putString'] = $putString;
  8. $new->variables['putBoolean'] = $putBoolean;
  9. $new->variables['putArray'] = $putArray;
  10.  
  11. $new->save();
  12. */
  13. var_dump($new->variables);
  14.  
  15. ?>


A że jest już późno jutro napiszę pozostałe przykłady...
NuLL
Lekki OT - Dziwna ta klasa jakas :|
sf
Moje uwagi:
- ścieżka do katalogu cache powinna być wewnątrz klasy, a nie jako define
- jeśli chodzi o czas to chyba lepiej wykorzystać strtotime niż ręcznie to wyliczać
- może do tworzenia XMLa użyć jakieś biblioteki generującej XML ?
- co z opcją by kilka osób naraz nie odświeżało cache?
- troche mi to przeszkadza, że do każdego cache trzeba tworzyć osobny obiekt.. brak mentody odczytu
Neotion
Cytat
Lekki OT - Dziwna ta klasa jakas :|

Specjalnie mi nie pomagasz takim komentarzem.

Jeżeli chodzi o czas to może rzeczywiście lepiej go przechowywać jako datę a nie jako time() ale wydało mi się to troszkę szybsze.

Cytat
co z opcją by kilka osób naraz nie odświeżało cache?

Nie rozumiem o co chodzi. Odświeżanie jest kontrolowane juz przez kod generujący ten cache a powyzsza klasa tylko stwierdza czy cache jest jescze ważny czy już nie.
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.