From ce659db8818a6c977ca1296142e5be78b930e57b Mon Sep 17 00:00:00 2001 From: christianklisch Date: Mon, 23 Dec 2013 17:48:16 +0100 Subject: [PATCH] initial commit --- .gitignore | 2 + .travic.yml | 5 ++ LICENSE | 15 ++++ PHPCache.class.php | 219 +++++++++++++++++++++++++++++++++++++++++++++ README.MD | 145 ++++++++++++++++++++++++++++++ composer.json | 18 ++++ 6 files changed, 404 insertions(+) create mode 100644 .gitignore create mode 100644 .travic.yml create mode 100644 LICENSE create mode 100644 PHPCache.class.php create mode 100644 README.MD create mode 100644 composer.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..77cdf78 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/cache +.project \ No newline at end of file diff --git a/.travic.yml b/.travic.yml new file mode 100644 index 0000000..f585de5 --- /dev/null +++ b/.travic.yml @@ -0,0 +1,5 @@ +language: php +php: + - 5.3 + - 5.4 + - 5.5 \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f911603 --- /dev/null +++ b/LICENSE @@ -0,0 +1,15 @@ +APACHE LICENSE + +Copyright (c) 2013 Christian Klisch + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/PHPCache.class.php b/PHPCache.class.php new file mode 100644 index 0000000..31d415e --- /dev/null +++ b/PHPCache.class.php @@ -0,0 +1,219 @@ + + * @copyright 2013 Christian Klisch + * @link https://github.com/christianklisch/phpcache + * @license https://github.com/christianklisch/phpcache/LICENSE + * @version 0.1.0 + * @package PHPCache + * + * APACHE LICENSE + * + * Copyright (c) 2013 Christian Klisch + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * PHPCache + * @package PHPCache + * @author Christian Klisch + * @since 0.1.0 + */ +class PHPCache { + + /** + * @var array + */ + protected $settings; + + /** + * @var array + */ + protected $primarykeys; + + /* * ****************************************************************************** + * Instantiation and Configuration + * ***************************************************************************** */ + + /** + * Constructor + * @param array $settings Associative array of caching settings + */ + public function __construct($settings = array()) { + // Setup caching + $this->settings = array_merge(static::getDefaultSettings(), $settings); + } + + /** + * Get default application settings + * @return array + */ + public static function getDefaultSettings() { + return array( + // directory + 'cacheDir' => 'cache', + // caching time in seconds + 'cacheTime' => '60', + // Debugging + 'debug' => true + ); + } + + /** + * Read and Write config + * @return string + */ + public function getConfig($name) { + return isset($this->settings[$name]) ? $this->settings[$name] : null; + } + + /** + * Setting get-functions for primary keys of classes + * @param array $primkeys Associative array of class primary-key-function + */ + public function setPrimaryKeys($primkeys = array()) { + $this->primarykeys = $primkeys; + } + + /* * ****************************************************************************** + * Logic functions + * ***************************************************************************** */ + + /** + * get cached value in time or return value + * @return object + */ + public function cacheVal($value, $id = null) { + if ($id == null) { + $id = $this->getIDfromOjb($value); + + if ($id == null && $this->getConfig('debug')) { + echo "no caching id"; + return $value; + } + } + + $cachefile = $this->getConfig('cacheDir') . '/' . $id; + $cachetime = $this->getConfig('cacheTime'); + + if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) { + $ser = file_get_contents($cachefile); + $val = unserialize($ser); + return $val; + } else { + $ser = serialize($value); + file_put_contents($cachefile, $ser); + return $value; + } + + if ($this->getConfig('debug')) + echo "no caching"; + } + + /** + * cache function result and return it + * @return object + */ + public function cacheFun($function) { + if ($this->getConfig('debug') && !is_callable($function)) + echo "no valid function"; + + $r = new ReflectionFunction($function); + $id = null; + + foreach ($r->getStaticVariables() as $key => $var) { + if ($key == 'key') + $id = $var; + } + + if (is_object($id)) + $id = $this->getIDfromOjb($id); + + if ($id == null && $this->getConfig('debug')) { + echo "no caching id"; + return $function(); + } + + $cachefile = $this->getConfig('cacheDir') . '/' . $id; + $cachetime = $this->getConfig('cacheTime'); + + if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) { + $ser = file_get_contents($cachefile); + $val = unserialize($ser); + return $val; + } else { + $value = $function(); + $ser = serialize($value); + file_put_contents($cachefile, $ser); + return $value; + } + + if ($this->getConfig('debug')) + echo "no caching"; + } + + /** + * check, if id or object in first parameter is cached. Returns true, if cached + * @return bool + */ + public function isCached($id) { + if ($id != null) { + $id = $this->getIDfromOjb($id); + } + + if ($id == null) + return false; + + $cachefile = $this->getConfig('cacheDir') . '/' . $id; + $cachetime = $this->getConfig('cacheTime'); + + if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) { + return true; + } + + return false; + } + + /** + * get id from object $value + * @return id + */ + private function getIDfromOjb($value) { + $id = null; + if ($this->primarykeys) { + foreach ($this->primarykeys as $key => $function) { + if (is_subclass_of($value, $key) || is_a($value, $key)) { + $id = $value->$function(); + break; + } + } + } + return $id; + } + + /** + * delete all cached files + */ + public function clearCache() { + $files = glob($this->getConfig('cacheDir') . '/*', GLOB_MARK); + foreach ($files as $file) { + unlink($file); + } + } +} + +?> \ No newline at end of file diff --git a/README.MD b/README.MD new file mode 100644 index 0000000..6bb1dc5 --- /dev/null +++ b/README.MD @@ -0,0 +1,145 @@ +# PHPCache v. 0.1.0 + +PHPCache is a simple file based object cache, caching big or complex calculated data in filesystem. + +Use it for: +* Increasing speed of web application +* Caching result objects from complex calculations +* Caching results from complex database queries +* Caching function calls +* Cache primitive data types, own objects, function results + +Features: +* Define caching time in seconds, cache directory +* Can be used with every variable / data (except. templates) +* Load data from cache or determine new data +* Clear caching directory + + +## Installation + +You can either install the script manually using the `require` method: + +```php +require 'PHPCache.php'; +``` + +This is currently the first release of PHPCache, so in this example you'll be able to update your script with any updates made to PHPCache. + +## Deploying + +Include the script in your project either with Composer or via the manual `require` method and create a new instance of the class, using the appropriate parameters if needed: + +```php +$image = new PHPCache(); +``` + +Possible parameters include: + +```php +$c = new PHPCache\PHPCache( + array($debug = true, $cacheDir = 'cache', $cacheTime = 10) +); +/** + * @param array $settings Associative array of caching settings + */ +``` + +### Primitive data type +Then cache an primitive data type with: + +```php +$myString = $c->cacheVal('String to cache','cachingID'); +``` + +This will cache the string of the first parameter into a file named by second parameter. Use the second parameter setting filename for primitive data types. + + +### Object data type + +Cache an object data type with: + +```php +$myObj = new FooBar(); +$obj = $c->cacheVal(myObj, myObj->getId()); +``` + +This will cache the object in the first parameter into a file named by second parameter. Use the second parameter setting id as filename for object cache. + +### Object data type with automatic ID-getter + +Define for each object type the id-key/primary key remove second id-parameter: + +```php +$myObj = new FooBar(); + +/** + * Setting get-functions for primary keys of classes + * @param array $primkeys Associative array of class primary-key-function + */ +$c->setPrimaryKeys(array( + 'FooBar' => 'getId' +)); + +$obj = $c->cacheVal(myObj); +``` + +Now the objects id is automatically determined by PHPCache logic. Caching configuration is + +### Check for cached data + +Check with the given ID if data is cached. Can be used to call a new cacheVal(). + +```php +/** + * check, if id or object in first parameter is cached. Returns true, if cached + * @return bool + */ + +if($c->isCached($id)) + $obj = $c->cacheVal(myObj, $id); +``` + +### Cache whole function calls + +Like the value-caching you can cache results of complex logical function calls. The defined function will only be called in case of absence cached function results. + +```php +/** + * cache function result and return it + * @return object + */ + +$key = 1110; + +$result = $cache->cacheFun( + function () use ($key, $logic) { + return $logic->getComplexResult(); + } +); + +echo "result: ".$result; +``` + +Please don't use function parametes. Submit your variables via the use()-keyword. It is important using one parameter named 'key' for caching. The name and count of other parameters is not important. Write the call of your complex logic inside the anonymous function. This code will be called, if your key isn't found in cache. + + +### Clear caching directory + +Delete all cached data in caching directory with: + +```php +/** + * delete all cached files + */ +$c->clearCache(); +``` + +## Contributors + +* Christian Klisch http://www.christian-klisch.de + + +## Copyright and license + +Copyright 2013 Christian Klisch, released under [the Apache](LICENSE). \ No newline at end of file diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..f596d7b --- /dev/null +++ b/composer.json @@ -0,0 +1,18 @@ +{ + "name": "christianklisch/phpcache", + "description": "A simple PHP caching class", + "keywords": "php","cache"], + "authors": [ + "name": "Christian Klisch", + "homepage": "http://www.christian-klisch.de/" + } + ], + "license": "Apache 2.0", + "homepage": "http://www.christian-klisch.de", + "autoload": { + "files": ["PHPCache.class.php"] + } + "require": { + "php": ">=5.3.0" + } +} \ No newline at end of file