Permalink
Browse files

First version

  • Loading branch information...
1 parent 8fb1ee9 commit 79fbde3c211e18b313661ac20047ae1ab5170d21 @thousandsofthem thousandsofthem committed May 9, 2012
Showing with 574 additions and 0 deletions.
  1. +5 −0 .gitignore
  2. +365 −0 IronCache.class.php
  3. +22 −0 LICENSE
  4. +105 −0 README.md
  5. +36 −0 TestCache.php
  6. +32 −0 build.php
  7. BIN iron_cache.phar
  8. +9 −0 sample_config.ini
View
5 .gitignore
@@ -0,0 +1,5 @@
+*.swp
+config.ini
+.DS_Store
+*.esproj/
+.idea/
View
365 IronCache.class.php
@@ -0,0 +1,365 @@
+<?php
+/**
+ * PHP client for IronCache
+ *
+ * @link https://github.com/iron-io/iron_cache_php
+ * @link http://www.iron.io/products/cache
+ * @link http://dev.iron.io/
+ * @version 0.0.1
+ * @package IronCache
+ * @copyright Feel free to copy, steal, take credit for, or whatever you feel like doing with this code. ;)
+ */
+
+
+class IronCache_Item {
+ private $value;
+ private $expires_in;
+ private $replace;
+ private $add;
+
+ const max_expires_in = 2592000;
+
+ /**
+ * Create a new item.
+ *
+ * @param array|string $item
+ * An array of item properties or a string of the item value.
+ * Fields in item array:
+ * Required:
+ * - value: string - The item data, as a string.
+ * Optional:
+ * - expires_in: integer - How long in seconds to keep the item on the cache before it is deleted. Default is 604,800 seconds (7 days). Maximum is 2,592,000 seconds (30 days).
+ * - replace: boolean - Will only work if key already exists.
+ * - add: boolean - Will only work if key does not exist.
+ */
+ function __construct($item) {
+ if(is_string($item) || is_integer($item)) {
+ $this->setValue($item);
+ } elseif(is_array($item)) {
+ $this->setValue($item['value']);
+ if(array_key_exists("replace", $item)) {
+ $this->setReplace($item['replace']);
+ }
+ if(array_key_exists("add", $item)) {
+ $this->setAdd($item['add']);
+ }
+ if(array_key_exists("expires_in", $item)) {
+ $this->setExpiresIn($item['expires_in']);
+ }
+ }
+ }
+
+ public function setValue($value) {
+ if(empty($value)) {
+ throw new InvalidArgumentException("Please specify a value");
+ } else {
+ $this->value = $value;
+ }
+ }
+
+ public function getValue() {
+ return $this->value;
+ }
+
+ public function setReplace($replace) {
+ $this->replace = $replace;
+ }
+
+ public function getReplace() {
+ return $this->replace;
+ }
+
+ public function setAdd($add) {
+ $this->add = $add;
+ }
+
+ public function getAdd() {
+ return $this->add;
+ }
+
+ public function setExpiresIn($expires_in) {
+ if($expires_in > self::max_expires_in) {
+ throw new InvalidArgumentException("Expires In can't be greater than ".self::max_expires_in.".");
+ } else {
+ $this->expires_in = $expires_in;
+ }
+ }
+
+ public function getExpiresIn(){
+ return $this->expires_in;
+ }
+
+ public function asArray() {
+ $array = array();
+ $array['value'] = $this->getValue();
+ if($this->getExpiresIn() != null) {
+ $array['expires_in'] = $this->getExpiresIn();
+ }
+ if($this->getReplace() != null) {
+ $array['replace'] = $this->getReplace();
+ }
+ if($this->getAdd() != null) {
+ $array['add'] = $this->getAdd();
+ }
+ return $array;
+ }
+}
+
+class IronCache extends IronCore{
+ protected $client_version = '0.0.1';
+ protected $client_name = 'iron_cache_php';
+ protected $product_name = 'iron_cache';
+ protected $default_values = array(
+ 'protocol' => 'https',
+ 'host' => 'cache-aws-us-east-1.iron.io',
+ 'port' => '443',
+ 'api_version' => '1',
+ );
+
+ private $cache_name;
+
+ /**
+ * @param string|array $config_file_or_options
+ * Array of options or name of config file.
+ * Fields in options array or in config:
+ *
+ * Required:
+ * - token
+ * - project_id
+ * Optional:
+ * - protocol
+ * - host
+ * - port
+ * - api_version
+ * @param string|null $cache_name set default cache name
+ */
+ function __construct($config_file_or_options, $cache_name = null){
+ $this->getConfigData($config_file_or_options);
+ $this->url = "{$this->protocol}://{$this->host}:{$this->port}/{$this->api_version}/";
+ $this->setCacheName($cache_name);
+ }
+
+ /**
+ * Switch active project
+ *
+ * @param string $project_id Project ID
+ * @throws InvalidArgumentException
+ */
+ public function setProjectId($project_id) {
+ if (!empty($project_id)){
+ $this->project_id = $project_id;
+ }
+ if (empty($this->project_id)){
+ throw new InvalidArgumentException("Please set project_id");
+ }
+ }
+
+ /**
+ * Set default cache name
+ *
+ * @param string $cache_name name of cache
+ * @throws InvalidArgumentException
+ */
+ public function setCacheName($cache_name) {
+ if (!empty($cache_name)){
+ $this->cache_name = $cache_name;
+ }
+
+ }
+
+ public function getCaches($page = 0){
+ $url = "projects/{$this->project_id}/caches";
+ $params = array();
+ if($page > 0) {
+ $params['page'] = $page;
+ }
+ $this->setJsonHeaders();
+ return self::json_decode($this->apiCall(self::GET, $url, $params));
+ }
+
+ /**
+ * Get information about cache.
+ * Also returns cache size.
+ *
+ * @param string $cache
+ * @return mixed
+ */
+ public function getCache($cache) {
+ $cache = self::encodeCache($cache);
+ $url = "projects/{$this->project_id}/caches/$cache";
+ $this->setJsonHeaders();
+ return self::json_decode($this->apiCall(self::GET, $url));
+ }
+
+ /**
+ * Push a item on the cache at 'key'
+ *
+ * Examples:
+ * <code>
+ * $cache->postItem("test_cache", 'default', "Hello world");
+ * </code>
+ * <code>
+ * $cache->postItem("test_cache", 'default', array(
+ * "value" => "Test Item",
+ * 'expires_in' => 2*24*3600, # 2 days
+ * "replace" => true
+ * ));
+ * </code>
+ *
+ * @param string $cache Name of the cache.
+ * @param string $key Item key.
+ * @param array|string $item
+ *
+ * @return mixed
+ */
+ public function putItem($cache, $key, $item) {
+ $cache = self::encodeCache($cache);
+ $key = self::encodeKey($key);
+ $itm = new IronCache_Item($item);
+ $req = $itm->asArray();
+ $url = "projects/{$this->project_id}/caches/$cache/items/$key";
+
+ $this->setJsonHeaders();
+ $res = $this->apiCall(self::PUT, $url, $req);
+ return self::json_decode($res);
+ }
+
+ /**
+ * Get item from cache by key
+ *
+ * @param string $cache Cache name
+ * @param string $key Cache key
+ * @return mixed|null single item or null
+ * @throws Http_Exception
+ */
+ public function getItem($cache, $key) {
+ $cache = self::encodeCache($cache);
+ $key = self::encodeKey($key);
+ $url = "projects/{$this->project_id}/caches/$cache/items/$key";
+
+ $this->setJsonHeaders();
+ try {
+ $res = $this->apiCall(self::GET, $url);
+ }catch (Http_Exception $e){
+ if ($e->getCode() == Http_Exception::NOT_FOUND){
+ return null;
+ }else{
+ throw $e;
+ }
+ }
+ return self::json_decode($res);
+ }
+
+ public function deleteItem($cache, $key) {
+ $cache = self::encodeCache($cache);
+ $key = self::encodeKey($key);
+ $url = "projects/{$this->project_id}/caches/$cache/items/$key";
+
+ $this->setJsonHeaders();
+ return self::json_decode($this->apiCall(self::DELETE, $url));
+ }
+
+ /**
+ * Atomically increments the value for key by amount.
+ * Can be used for both increment and decrement by passing a negative value.
+ * The value must exist and must be an integer.
+ * The number is treated as an unsigned 64-bit integer.
+ * The usual overflow rules apply when adding, but subtracting from 0 always yields 0.
+ *
+ * @param string $cache
+ * @param string $key
+ * @param int $amount Change by this value
+ * @return mixed|void
+ */
+ public function incrementItem($cache, $key, $amount = 1){
+ $cache = self::encodeCache($cache);
+ $key = self::encodeKey($key);
+ $url = "projects/{$this->project_id}/caches/$cache/items/$key/increment";
+ $params = array(
+ 'amount' => $amount
+ );
+ $this->setJsonHeaders();
+ return self::json_decode($this->apiCall(self::POST, $url, $params));
+ }
+
+
+ /**
+ * Shortcut for getItem($cache, $key)
+ * Please set $cache name before use by setCacheName() method
+ *
+ * @param string $key
+ * @return mixed|null
+ * @throws InvalidArgumentException
+ */
+ public function get($key){
+ return $this->getItem($this->cache_name, $key);
+ }
+
+ /**
+ * Shortcut for postItem($cache, $key, $item)
+ * Please set $cache name before use by setCacheName() method
+ *
+ * @param string $key
+ * @param array|string $item
+ * @return mixed
+ * @throws InvalidArgumentException
+ */
+ public function put($key, $item){
+ return $this->putItem($this->cache_name, $key, $item);
+ }
+
+ /**
+ * Shortcut for deleteItem($cache, $key)
+ * Please set $cache name before use by setCacheName() method
+ *
+ * @param string $key
+ * @return mixed|void
+ * @throws InvalidArgumentException
+ */
+ public function delete($key){
+ return $this->deleteItem($this->cache_name, $key);
+ }
+
+ /**
+ * Shortcut for incrementItem($cache, $key, $amount)
+ * Please set $cache name before use by setCacheName() method
+ *
+ * @param string $key
+ * @param int $amount
+ * @return mixed|void
+ * @throws InvalidArgumentException
+ */
+ public function increment($key, $amount = 1){
+ if (empty($this->cache_name)){
+ throw new InvalidArgumentException("Please set cache_name");
+ }
+ return $this->incrementItem($this->cache_name, $key, $amount);
+ }
+
+ /* PRIVATE FUNCTIONS */
+
+ private static function encodeCache($cache){
+ if (empty($cache)){
+ throw new InvalidArgumentException('Please set $cache variable');
+ }
+ return rawurlencode($cache);
+ }
+
+ private static function encodeKey($key){
+ if (empty($key)){
+ throw new InvalidArgumentException('Please set $key variable');
+ }
+ return rawurlencode($key);
+ }
+
+
+ private function setJsonHeaders(){
+ $this->setCommonHeaders();
+ }
+
+ private function setPostHeaders(){
+ $this->setCommonHeaders();
+ $this->headers['Content-Type'] ='multipart/form-data';
+ }
+
+}
View
22 LICENSE
@@ -0,0 +1,22 @@
+Copyright (c) 2012, Iron.io, Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice,
+this list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above copyright notice,
+this list of conditions and the following disclaimer in the documentation
+and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
View
105 README.md
@@ -0,0 +1,105 @@
+IronCache PHP Client
+-------------
+
+Getting Started
+==============
+
+## Get credentials
+To start using iron_cache_php, you need to sign up and get an oauth token.
+
+1. Go to http://iron.io/ and sign up.
+2. Get an Oauth Token at http://hud.iron.io/tokens
+
+## Install iron_cache_php
+
+There are two ways to use iron_cache_php:
+
+#### Using precompiled phar archive:
+
+Copy `iron_cache.phar` to target directory and include it:
+
+```php
+<?php
+require_once "phar://iron_cache.phar";
+```
+
+Please note, [phar](http://php.net/manual/en/book.phar.php) extension available by default only from php 5.3.0
+For php 5.2 you should install phar manually or use second option.
+
+#### Using classes directly
+
+1. Copy `IronCache.class.php` to target directory
+2. Grab `IronCore.class.php` [there](https://github.com/iron-io/iron_core_php) and copy to target directory
+3. Include both of them:
+
+```php
+<?php
+require_once "IronCore.class.php"
+require_once "IronCache.class.php"
+```
+
+## Configure
+Three ways to configure IronCache:
+
+* Passing array with options:
+
+```php
+<?php
+$cache = new IronCache(array(
+ 'token' => 'XXXXXXXXX',
+ 'project_id' => 'XXXXXXXXX'
+));
+```
+* Passing ini file name which stores your configuration options. Rename sample_config.ini to config.ini and include your Iron.io credentials (`token` and `project_id`):
+
+```php
+<?php
+$cache = new IronCache('config.ini');
+```
+
+* Automatic config search - pass zero arguments to constructor and library will try to find config file in following locations:
+
+ * `iron.ini` in current directory
+ * `iron.json` in current directory
+ * `IRON_CACHE_TOKEN`, `IRON_CACHE_PROJECT_ID` and other environment variables
+ * `IRON_TOKEN`, `IRON_PROJECT_ID` and other environment variables
+ * `.iron.ini` in user's home directory
+ * `.iron.json` in user's home directory
+
+The Basics
+=========
+
+**Put** an item in the cache:
+
+```php
+<?php
+$res = $cache->put("mykey", "hello world!");
+```
+
+**Get** an item from the cache:
+
+```php
+<?php
+$item = $cache->get("mykey");
+```
+
+**Increment** an item value in the cache:
+
+```php
+<?php
+$res = $cache->increment("mykey", 1);
+```
+
+**Delete** an item from the cache:
+```php
+<?php
+$res = $cache->delete("mykey");
+```
+
+Cache Selection
+===============
+
+Select cache before interacting with items
+* In constructor: `$cache = new IronCache('config.ini', 'my_cache');`
+* By method: `$cache->setCacheName('my_cache');`
+* Do it later when you need: `$cache->getItem('my_cache','my_key');`
View
36 TestCache.php
@@ -0,0 +1,36 @@
+<?php
+
+include("../iron_core_php/IronCore.class.php");
+include("IronCache.class.php");
+
+$cache = new IronCache('config.ini');
+$cache->ssl_verifypeer = false;
+#$cache->debug_enabled = true;
+$cache->setCacheName('cache #1');
+$key = "key #1";
+
+echo "Put item on cache:";
+$res = $cache->put($key, 777);
+print_r($res);
+
+echo "\nGet item from cache:";
+$item = $cache->get($key);
+print_r($item);
+
+echo "Increment item on cache:";
+$res = $cache->increment($key, -222);
+print_r($res);
+
+echo "\nGet item from cache:";
+$item = $cache->get($key);
+print_r($item);
+
+echo "\nRemoving item from cache:";
+$res = $cache->delete($key);
+print_r($res);
+
+echo "\nGet item from cache:";
+$item = $cache->get($key);
+var_dump($item);
+
+echo "\nEnd\n";
View
32 build.php
@@ -0,0 +1,32 @@
+<?php
+/**
+ * This script creates .phar archive with all required dependencies.
+ * Archive usage:
+ * include("phar://iron_cache.phar");
+ * or
+ * include("phar://".dirname(__FILE__)."/iron_cache.phar");
+ */
+
+@unlink('iron_cache.phar');
+
+$phar = new Phar('iron_cache.phar');
+
+# Loader
+$phar->setStub('<?php
+Phar::mapPhar("iron_cache.phar");
+require "phar://iron_cache.phar/IronCore.class.php";
+require "phar://iron_cache.phar/IronCache.class.php";
+__HALT_COMPILER(); ?>');
+
+# Files
+$phar->addFile('../iron_core_php/IronCore.class.php','IronCore.class.php');
+$phar->addFile('IronCache.class.php');
+$phar->addFile('LICENSE', 'LICENSE');
+
+echo "\ndone - ".(round(filesize('iron_cache.phar')/1024,2))." KB\n";
+
+# Verification
+require "phar://iron_cache.phar";
+$cache = new IronCache('config.ini');
+
+echo "Build finished successfully\n";
View
BIN iron_cache.phar
Binary file not shown.
View
9 sample_config.ini
@@ -0,0 +1,9 @@
+[iron_cache]
+token = ENTER_YOUR_TOKEN_HERE
+project_id = ENTER_YOUR_PROJECT_ID_HERE
+; Optional fields:
+; protocol = https
+; api_version = 1
+; host = cache-aws-us-east-1.iron.io
+; port = 443
+

0 comments on commit 79fbde3

Please sign in to comment.