Implementation code for APC and file cache classes in PHP

Source: Internet
Author: User
  1. Class Cacheexception extends Exception {}

  2. /**
  3. * Caching Abstract classes
  4. */
  5. Abstract class Cache_abstract {
  6. /**
  7. * Read Cache variables
  8. *
  9. * @param string $key cache subscript
  10. * @return Mixed
  11. */
  12. Abstract public Function fetch ($KEY);

  13. /**

  14. * Cache Variables
  15. *
  16. * @param string $key cache variable Subscript
  17. * @param string $value The value of the cache variable
  18. * @return BOOL
  19. */
  20. Abstract Public function Store ($key, $value);

  21. /**

  22. * Delete Cache variables
  23. *
  24. * @param string $key cache subscript
  25. * @return Cache_abstract
  26. */
  27. Abstract Public Function Delete ($key);

  28. /**

  29. * Clear (delete) except all caches
  30. *
  31. * @return Cache_abstract
  32. */
  33. Abstract public Function clear ();

  34. /**

  35. * Lock Cache variables
  36. *
  37. * @param string $key cache subscript
  38. * @return Cache_abstract
  39. */
  40. Abstract Public Function lock ($key);
  41. /**
  42. * Cache Variable Unlocked
  43. *
  44. * @param string $key cache subscript
  45. * @return Cache_abstract
  46. */
  47. Abstract public Function unlock ($key);
  48. /**
  49. * Gets whether the cache variable is locked
  50. *
  51. * @param string $key cache subscript
  52. * @return BOOL
  53. */
  54. Abstract public Function isLocked ($key);
  55. /**
  56. * Make sure not locked status
  57. * Up to $tries sleep waiting to be unlocked, timeout skipped and unlocked
  58. *
  59. * @param string $key cache subscript
  60. */
  61. Public Function Checklock ($key) {
  62. if (! $this->islocked ($key)) {
  63. return $this;
  64. }
  65. $tries = 10;
  66. $count = 0;
  67. do {
  68. Usleep (200);
  69. $count + +;
  70. } while ($count <= $tries && $this->islocked ($key)); Do up to 10 sleep waits to unlock, timeout to skip and unlock
  71. $this->islocked ($key) && $this->unlock ($key);
  72. return $this;
  73. }
  74. }

  75. /**

  76. * APC Extended Cache implementation
  77. *
  78. * @by bbs.it-home.org
  79. * @category Mjie
  80. * @package Cache
  81. * @license New BSD License
  82. * @version $Id: cache/apc.php version number 2010-04-18 23:02 Cmpan $
  83. */
  84. Class Cache_apc extends Cache_abstract {

  85. protected $_prefix = ' cache.mjie.net ';

  86. Public Function __construct () {

  87. if (!function_exists (' Apc_cache_info ')) {
  88. throw new Cacheexception (' APC extension didn\ ' t installed ');
  89. }
  90. }

  91. /**

  92. * Save Cache variables
  93. *
  94. * @param string $key
  95. * @param mixed $value
  96. * @return BOOL
  97. */
  98. Public function Store ($key, $value) {
  99. Return Apc_store ($this->_storagekey ($key), $value);
  100. }

  101. /**

  102. * Read Cache
  103. *
  104. * @param string $key
  105. * @return Mixed
  106. */
  107. Public function Fetch ($key) {
  108. Return Apc_fetch ($this->_storagekey ($key));
  109. }

  110. /**

  111. * Clear Cache
  112. *
  113. * @return CACHE_APC
  114. */
  115. Public Function Clear () {
  116. Apc_clear_cache ();
  117. return $this;
  118. }

  119. /**

  120. * Delete Cache unit
  121. *
  122. * @return CACHE_APC
  123. */
  124. Public Function Delete ($key) {
  125. Apc_delete ($this->_storagekey ($key));
  126. return $this;
  127. }

  128. /**

  129. * Whether the cache unit is locked
  130. *
  131. * @param string $key
  132. * @return BOOL
  133. */
  134. Public Function isLocked ($key) {
  135. if (Apc_fetch ($this->_storagekey ($key). '. Lock ')) = = = = False) {
  136. return false;
  137. }
  138. return true;
  139. }

  140. /**

  141. * Lock Cache Unit
  142. *
  143. * @param string $key
  144. * @return CACHE_APC
  145. */
  146. Public function Lock ($key) {
  147. Apc_store ($this->_storagekey ($key). '. Lock ', ', 5 ';
  148. return $this;
  149. }

  150. /**

  151. * Cache Unit Unlocked
  152. *
  153. * @param string $key
  154. * @return CACHE_APC
  155. */
  156. Public function Unlock ($key) {
  157. Apc_delete ($this->_storagekey ($key). '. Lock ');
  158. return $this;
  159. }

  160. /**

  161. * Full Cache Name
  162. *
  163. * @param string $key
  164. * @return String
  165. */
  166. Private Function _storagekey ($key) {
  167. Return $this->_prefix. '_' . $key;
  168. }
  169. }
  170. /**
  171. * File Cache implementation
  172. *
  173. * @by bbs.it-home.org
  174. * @category Mjie
  175. * @package Cache
  176. * @license New BSD License
  177. * @version $Id: cache/file.php version number 2010-04-18 16:46 Cmpan $
  178. */
  179. Class Cache_file extends Cache_abstract {

  180. Protected $_cachesdir = ' cache ';

  181. Public Function __construct () {

  182. if (defined (' Data_dir ')) {
  183. $this->_setcachedir (Data_dir. '/cache ');
  184. }
  185. }

  186. /**

  187. * Get cache files
  188. *
  189. * @param string $key
  190. * @return String
  191. */
  192. protected function _getcachefile ($key) {
  193. Return $this->_cachesdir. '/' . substr ($key, 0, 2). '/' . $key. '. php ';
  194. }
  195. /**
  196. * Read Cache variables
  197. * To prevent information disclosure, the cache file format is PHP file and begins with " "
  198. *
  199. * @param string $key cache subscript
  200. * @return Mixed
  201. */
  202. Public function Fetch ($key) {
  203. $cacheFile = Self::_getcachefile ($key);
  204. if (file_exists ($cacheFile) && is_readable ($cacheFile)) {
  205. Return Unserialize (@file_get_contents ($cacheFile, False, NULL, 13));
  206. }
  207. return false;
  208. }
  209. /**
  210. * Cache Variables
  211. * To prevent information disclosure, the cache file format is PHP file and begins with " "
  212. *
  213. * @param string $key cache variable Subscript
  214. * @param string $value The value of the cache variable
  215. * @return BOOL
  216. */
  217. Public function Store ($key, $value) {
  218. $cacheFile = Self::_getcachefile ($key);
  219. $cacheDir = DirName ($cacheFile);
  220. if (!is_dir ($cacheDir)) {
  221. if ([url=mailto:! @mkdir ($cacheDir]! @mkdir ($cacheDir [/url], 0755, True) {
  222. throw new Cacheexception ("Could not make cache directory");
  223. }
  224. }
  225. Return @file_put_contents ($cacheFile, " . Serialize ($value));
  226. }
  227. /**
  228. * Delete Cache variables
  229. *
  230. * @param string $key cache subscript
  231. * @return Cache_file
  232. */
  233. Public Function Delete ($key) {
  234. if (empty ($key)) {
  235. throw new Cacheexception ("Missing argument 1 for Cache_file::d elete ()");
  236. }
  237. $cacheFile = Self::_getcachefile ($key);
  238. if ([url=mailto:! @unlink ($cacheFile]! @unlink ($cacheFile [/url]) {
  239. throw new Cacheexception ("Cache file could not being deleted");
  240. }
  241. return $this;
  242. }
  243. /**
  244. * Whether the cache unit is locked
  245. *
  246. * @param string $key
  247. * @return BOOL
  248. */
  249. Public Function isLocked ($key) {
  250. $cacheFile = Self::_getcachefile ($key);
  251. Clearstatcache ();
  252. Return File_exists ($cacheFile. '. Lock ');
  253. }
  254. /**
  255. * Lock
  256. *
  257. * @param string $key
  258. * @return Cache_file
  259. */
  260. Public function Lock ($key) {
  261. $cacheFile = Self::_getcachefile ($key);
  262. $cacheDir = DirName ($cacheFile);
  263. if (!is_dir ($cacheDir)) {
  264. if ([url=mailto:! @mkdir ($cacheDir]! @mkdir ($cacheDir [/url], 0755, True) {
  265. if (!is_dir ($cacheDir)) {
  266. throw new Cacheexception ("Could not make cache directory");
  267. }
  268. }
  269. }
  270. Setting access and modification times for cache lock files
  271. @touch ($cacheFile. '. Lock ');
  272. return $this;
  273. }
  274. /**
  275. * Unlock
  276. *
  277. * @param string $key
  278. * @return Cache_file
  279. */
  280. Public function Unlock ($key) {
  281. $cacheFile = Self::_getcachefile ($key);
  282. @unlink ($cacheFile. '. Lock ');
  283. return $this;
  284. }
  285. /**
  286. * Set File cache directory
  287. * @param string $dir
  288. * @return Cache_file
  289. */
  290. protected function _setcachedir ($dir) {
  291. $this->_cachesdir = RTrim (str_replace (' \ \ ', '/', trim ($dir)), '/');
  292. Clearstatcache ();
  293. if (!is_dir ($this->_cachesdir)) {
  294. mkdir ($this->_cachesdir, 0755, true);
  295. }
  296. //
  297. return $this;
  298. }
  299. /**
  300. * Clear All Caches
  301. *
  302. * @return Cache_file
  303. */
  304. Public Function Clear () {
  305. Traverse Directory Cleanup Cache
  306. $cacheDir = $this->_cachesdir;
  307. $d = Dir ($cacheDir);
  308. while (false!== ($entry = $d->read ())) {
  309. if ('. ' = = $entry [0]) {
  310. Continue
  311. }
  312. $cacheEntry = $cacheDir. '/' . $entry;
  313. if (Is_file ($cacheEntry)) {
  314. @unlink ($cacheEntry);
  315. } elseif (Is_dir ($cacheEntry)) {
  316. Cache folder has level two
  317. $d 2 = dir ($cacheEntry);
  318. while (false!== ($entry = $d 2->read ())) {
  319. if ('. ' = = $entry [0]) {
  320. Continue
  321. }
  322. $cacheEntry. = '/'. $entry;
  323. if (Is_file ($cacheEntry)) {
  324. @unlink ($cacheEntry);
  325. }
  326. }
  327. $d 2->close ();
  328. }
  329. }
  330. $d->close ();
  331. return $this;
  332. }
  333. }
  334. /**
  335. * Data structure of the cache unit
  336. * Array (
  337. * ' Time ' () ', ' (),//timestamp when the cache was written
  338. * ' expire ' = $expire,//cache expiry time
  339. * ' valid ' = = true,//cache is valid
  340. * ' data ' = $value//Cached value
  341. * );
  342. */
  343. Final class Cache {
  344. /**
  345. * Cache Expiration Time Length (s)
  346. *
  347. * @var int
  348. */
  349. Private $_expire = 3600;
  350. /**
  351. * Cache Processing Class
  352. *
  353. * @var Cache_abstract
  354. */
  355. Private $_storage = null;
  356. /**
  357. * @return Cache
  358. */
  359. static public Function Createcache ($cacheClass = ' cache_file ') {
  360. return new self ($cacheClass);
  361. }
  362. Private function __construct ($cacheClass) {
  363. $this->_storage = new $cacheClass ();
  364. }
  365. /**
  366. * Set Cache
  367. *
  368. * @param string $key
  369. * @param mixed $value
  370. * @param int $expire
  371. */
  372. Public function set ($key, $value, $expire = False) {
  373. if (! $expire) {
  374. $expire = $this->_expire;
  375. }
  376. $this->_storage->checklock ($key);
  377. $data = Array (' time ' = = Time (), ' expire ' = = $expire, ' valid ' = = True, ' data ' = $value);
  378. $this->_storage->lock ($key);
  379. try {
  380. $this->_storage->store ($key, $data);
  381. $this->_storage->unlock ($key);
  382. } catch (Cacheexception $e) {
  383. $this->_storage->unlock ($key);
  384. Throw $e;
  385. }
  386. }
  387. /**
  388. * Read Cache
  389. *
  390. * @param string $key
  391. * @return Mixed
  392. */
  393. Public function Get ($key) {
  394. $data = $this->fetch ($key);
  395. if ($data && $data [' valid '] && $data [' isexpired ']) {
  396. return $data [' data '];
  397. }
  398. return false;
  399. }
  400. /**
  401. * Read cache, including outdated and invalid, to obtain a complete storage structure
  402. *
  403. * @param string $key
  404. */
  405. Public function Fetch ($key) {
  406. $this->_storage->checklock ($key);
  407. $data = $this->_storage->fetch ($key);
  408. if ($data) {
  409. $data [' isexpired '] = (Time ()-$data [' time ']) > $data [' Expire ']? True:false;
  410. return $data;
  411. }
  412. return false;
  413. }
  414. /**
  415. * Delete Cache
  416. *
  417. * @param string $key
  418. */
  419. Public Function Delete ($key) {
  420. $this->_storage->checklock ($key)
  421. ->lock ($key)
  422. ->delete ($key)
  423. ->unlock ($key);
  424. }

  425. Public Function Clear () {

  426. $this->_storage->clear ();
  427. }
  428. /**
  429. * Set the cache to be invalid
  430. *
  431. * @param string $key
  432. */
  433. Public Function Setinvalidate ($key) {
  434. $this->_storage->checklock ($key)
  435. ->lock ($key);
  436. try {
  437. $data = $this->_storage->fetch ($key);
  438. if ($data) {
  439. $data [' valid '] = false;
  440. $this->_storage->store ($key, $data);
  441. }
  442. $this->_storage->unlock ($key);
  443. } catch (Cacheexception $e) {
  444. $this->_storage->unlock ($key);
  445. Throw $e;
  446. }
  447. }

  448. /**

  449. * Set cache expiration Time (s)
  450. *
  451. * @param int $expire
  452. */
  453. Public Function Setexpire ($expire) {
  454. $this->_expire = (int) $expire;
  455. return $this;
  456. }
  457. }
  458. ?>

Copy Code
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.