Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
christianklisch committed Dec 23, 2013
0 parents commit ce659db
Show file tree
Hide file tree
Showing 6 changed files with 404 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
@@ -0,0 +1,2 @@
/cache
.project
5 changes: 5 additions & 0 deletions .travic.yml
@@ -0,0 +1,5 @@
language: php
php:
- 5.3
- 5.4
- 5.5
15 changes: 15 additions & 0 deletions 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.
219 changes: 219 additions & 0 deletions PHPCache.class.php
@@ -0,0 +1,219 @@
<?php

/**
* PHPCache - a PHP caching class
*
* @author Christian Klisch <info@christian-klisch.de>
* @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);
}
}
}

?>
145 changes: 145 additions & 0 deletions 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).

0 comments on commit ce659db

Please sign in to comment.