Write a Cache model in Lithium php framework with mongodb

This is a simple code for creating cache data in mongodb using Lithium php framework.
The data will be kept 1 hour as default.

<?php

namespace app\models;

class Caches extends \lithium\data\Model {
	/**
	*
	* @param unknown $type this is to specify the category of the data
	* @param unknown $key this is the key of the cache
	* @return return the cache if it exists and is not expired
	*/
	public function getArrayCache($type, $key) {
	 // Check cache time
		$cache = Caches::find('first', array(
				'fields' => array('created'),
				'conditions' => array(
						'type' => $type,
						'key' => $key
				)
		));

		if ($cache == null) {
			return null;
		}
		$currentTime = date('Y-m-d H:i:s');
		$duration = strtotime($currentTime) - strtotime($cache->created);
		if ($duration > 60 * 60 * 1 /* 1 hour */) {
		    // Delete expired cache
			Caches::remove(array(
			'type' => $type,
			'key' => $key
			));

			return null;
		}

		$cache = Caches::find('first', array(
				'fields' => array('cache'),
				'conditions' => array(
						'type' => $type,
						'key' => $key
				)
		));
		return json_decode($cache->cache, true);
	}

	/**
	 *
	 * @param unknown $type this is to specify the category of the data
	 * @param unknown $key this is the key of the cache
	 * @param unknown $arrayData an array or object wanted to cache
	 */
	public function putArrayCache($type, $key, $arrayData) {
		Caches::remove(array(
			'type' => $type,
			'key' => $key
		));
				
		$cache = array(
				'type' => $type,
				'key' => $key,
				'created' => date('Y-m-d H:i:s'),
				'cache' => json_encode($arrayData)
		);
		Caches::create($cache)->save();
	}
}

?>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s