Browse files

Merge tag 'v0.10.1' of https://github.com/tedivm/Stash into HEAD

Version 0.10.1
  • Loading branch information...
2 parents 2fd629c + 5c4ef1d commit 24bbc64982fd73995c1f11665ad9df7744464c38 @pwhelan pwhelan committed Feb 3, 2013
Showing with 1,229 additions and 1,217 deletions.
  1. +4 −0 .gitignore
  2. +2 −1 .travis.yml
  3. +8 −4 README.md
  4. +4 −1 composer.json
  5. +0 −103 src/Stash/Box.php
  6. +6 −6 src/Stash/{Handler → Driver}/Apc.php
  7. +77 −0 src/Stash/Driver/BlackHole.php
  8. +33 −33 src/Stash/{Handler/MultiHandler.php → Driver/Composite.php}
  9. +16 −16 src/Stash/{Handler/HandlerInterface.php → Driver/DriverInterface.php}
  10. +3 −3 src/Stash/{Handler → Driver}/Ephemeral.php
  11. +8 −7 src/Stash/{Handler → Driver}/FileSystem.php
  12. +8 −8 src/Stash/{Handler → Driver}/Memcache.php
  13. +50 −50 src/Stash/{Handler → Driver}/Sqlite.php
  14. +1 −1 src/Stash/{Handler → Driver}/Sub/Memcache.php
  15. +1 −1 src/Stash/{Handler → Driver}/Sub/Memcached.php
  16. +26 −26 src/Stash/{Handler → Driver}/Sub/Sqlite.php
  17. +6 −6 src/Stash/{Handler → Driver}/Sub/SqlitePdo.php
  18. +2 −2 src/Stash/{Handler → Driver}/Sub/SqlitePdo2.php
  19. +5 −5 src/Stash/{Handler → Driver}/Xcache.php
  20. +80 −0 src/Stash/Drivers.php
  21. +0 −79 src/Stash/Handlers.php
  22. +81 −194 src/Stash/{Cache.php → Item.php}
  23. +0 −134 src/Stash/Manager.php
  24. +70 −29 src/Stash/Pool.php
  25. +234 −0 src/Stash/Session.php
  26. +30 −0 src/Stash/Session/SessionHandlerInterface.php
  27. +8 −8 src/Stash/Utilities.php
  28. +67 −123 tests/Stash/Test/AbstractCacheTest.php
  29. +0 −68 tests/Stash/Test/BoxTest.php
  30. +15 −14 tests/Stash/Test/CacheExceptionTest.php
  31. +41 −41 tests/Stash/Test/{Handler/AbstractHandlerTest.php → Driver/AbstractDriverTest.php}
  32. +7 −7 tests/Stash/Test/{Handler → Driver}/ApcTest.php
  33. +53 −0 tests/Stash/Test/Driver/BlackHoleTest.php
  34. +20 −20 tests/Stash/Test/{Handler/MultiHandlerTest.php → Driver/CompositeTest.php}
  35. +3 −3 tests/Stash/Test/{Handler → Driver}/EphemeralTest.php
  36. +3 −3 tests/Stash/Test/{Handler → Driver}/FileSystemTest.php
  37. +9 −10 tests/Stash/Test/{Handler → Driver}/MemcacheAnyTest.php
  38. +14 −16 tests/Stash/Test/{Handler → Driver}/MemcacheTest.php
  39. +1 −1 tests/Stash/Test/{Handler → Driver}/MemcachedTest.php
  40. +9 −10 tests/Stash/Test/{Handler → Driver}/SqliteAnyTest.php
  41. +8 −8 tests/Stash/Test/{Handler → Driver}/SqlitePdoSqlite2Test.php
  42. +8 −8 tests/Stash/Test/{Handler → Driver}/SqlitePdoSqlite3Test.php
  43. +8 −8 tests/Stash/Test/{Handler → Driver}/SqliteSqlite2Test.php
  44. +3 −3 tests/Stash/Test/{Handler → Driver}/XcacheTest.php
  45. +44 −0 tests/Stash/Test/DriversTest.php
  46. +2 −2 tests/Stash/Test/Exception/ExceptionTest.php
  47. +0 −44 tests/Stash/Test/HandlersTest.php
  48. +3 −3 tests/Stash/Test/{CacheTest.php → ItemTest.php}
  49. +0 −71 tests/Stash/Test/ManagerTest.php
  50. +19 −19 tests/Stash/Test/PoolTest.php
  51. +118 −0 tests/Stash/Test/SessionTest.php
  52. +1 −1 tests/Stash/Test/UtilitiesTest.php
  53. +10 −17 tests/bootstrap.php
View
4 .gitignore
@@ -1,2 +1,6 @@
phpunit.xml
Stash.komodoproject
+
+vendor
+report
+.idea
View
3 .travis.yml
@@ -5,7 +5,8 @@ php:
- 5.4
before_script:
+ - composer install --dev
- php tests/travis.setup.php
-script: phpunit --verbose
+script: phpunit --verbose --coverage-text
View
12 README.md
@@ -2,9 +2,13 @@
[![Build Status](https://secure.travis-ci.org/tedivm/Stash.png?branch=master)](http://travis-ci.org/tedivm/Stash)
-Stash makes it easy to speed up your code by caching the results of expensive functions or code. Certain
-actions, like database queries or calls to external APIs, take a lot of time to run but tend to have the
-same results over short periods of time. This makes it much more efficient to store the results and call
+Stash makes it easy to speed up your code by caching the results of expensive
+functions or code. Certain actions, like database queries or calls to external
+APIs, take a lot of time to run but tend to have the same results over short
+periods of time. This makes it much more efficient to store the results and call
them back up later.
-Visit [stash.tedivm.com](http://stash.tedivm.com) for the full documentation.
+Visit [stash.tedivm.com](http://stash.tedivm.com) for the current documentation.
+
+The [development documentation](http://stash.tedivm.com/dev/) is available for
+testing new releases, but is not considered stable.
View
5 composer.json
@@ -19,6 +19,9 @@
"php": ">=5.3.0"
},
"autoload": {
- "psr-0": {"Stash": "src/"}
+ "psr-0": {
+ "Stash": "src/",
+ "Stash\\Test": "tests/"
+ }
}
}
View
103 src/Stash/Box.php
@@ -1,103 +0,0 @@
-<?php
-
-/*
- * This file is part of the Stash package.
- *
- * (c) Robert Hafner <tedivm@tedivm.com>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Stash;
-
-use Stash\Handler\HandlerInterface;
-
-/**
- * StashBox makes managing a simply cache system easier by encapsulating certain commonly used tasks. StashBox also
- * makes it easier to reuse a handler object for each Stash instance. The downside to StashBox is that it only works
- * with one handler at a time, so systems with multiple cache pools will want to use the StashManager class instead.
- *
- * @package Stash
- * @author Robert Hafner <tedivm@tedivm.com>
- */
-class Box
-{
- static protected $handler;
-
-
- /**
- * Takes the same arguments as the Stash->setupKey() function and returns with a new Stash object. If a handler
- * has been set for this class then it is used, otherwise the Stash object will be set to use script memory only.
- * Any Stash object set for this class uses the 'stashbox' namespace.
- *
- * @example $cache = new StashBox::getCache('permissions', 'user', '4', '2');
- *
- * @param string|array $key, $key, $key...
- * @return Stash
- */
- static function getCache()
- {
- $args = func_get_args();
-
- // check to see if a single array was used instead of multiple arguments
- if (count($args) == 1 && is_array($args[0])) {
- $args = $args[0];
- }
-
- $handler = (isset(self::$handler)) ? self::$handler : null;
- $stash = new Cache($handler, 'stashbox');
-
- if (count($args) > 0) {
- $stash->setupKey($args);
- }
-
- return $stash;
- }
-
- /**
- * Works exactly like the Stash->clear() function, except it can be called as a single function which will build the
- * Stash object internally, load the handler, and clear the portion of the cache pool specified all in one call.
- *
- * @param null|string|array $key, $key, $key...
- * @return bool success
- */
- static function clearCache()
- {
- $stash = self::getCache(func_get_args());
- return $stash->clear();
- }
-
- /**
- * Works exactly like the Stash->purge() function, except it can be called as a single function which will build the
- * Stash object internally, load the handler, and run the purge function all in one call.
- *
- * @return bool success
- */
- static function purgeCache()
- {
- $stash = self::getCache();
- return $stash->purge();
- }
-
- /**
- * Returns a list of all available handlers that are registered with the system.
- *
- * @return array ShortName => Class
- */
- static function getCacheHandlers()
- {
- return Handlers::getHandlers();
- }
-
- /**
- * Sets a handler for each Stash object created by this class. This allows the handlers to be created just once
- * and reused, making it much easier to incorporate caching into any code.
- *
- * @param HandlerInterface $handler
- */
- static function setHandler(HandlerInterface $handler)
- {
- self::$handler = $handler;
- }
-}
View
12 src/Stash/Handler/Apc.php → src/Stash/Driver/Apc.php
@@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/
-namespace Stash\Handler;
+namespace Stash\Driver;
use Stash;
use Stash\Exception\RuntimeException;
@@ -20,13 +20,13 @@
* @package Stash
* @author Robert Hafner <tedivm@tedivm.com>
*/
-class Apc implements HandlerInterface
+class Apc implements DriverInterface
{
protected $ttl = 300;
protected $apcNamespace;
/**
- * This function should takes an array which is used to pass option values to the handler.
+ * This function should takes an array which is used to pass option values to the driver.
*
* * ttl - This is the maximum time the item will be stored.
* * namespace - This should be used when multiple projects may use the same library.
@@ -47,7 +47,7 @@ public function __construct(array $options = array())
}
/**
- * Empty destructor to maintain a standardized interface across all handlers.
+ * Empty destructor to maintain a standardized interface across all drivers.
*
*/
public function __destruct()
@@ -75,7 +75,7 @@ public function getData($key)
/**
* This function takes an array as its first argument and the expiration time as the second. This array contains two
* items, "createdOn" describing the first time the item was called and "return", which is the data that needs to be
- * stored. This function needs to store that data in such a way that it can be retrieced exactly as it was sent. The
+ * stored. This function needs to store that data in such a way that it can be retrieved exactly as it was sent. The
* expiration time needs to be stored with this data.
*
* @param array $key
@@ -135,7 +135,7 @@ public function purge()
}
/**
- * This handler is available iff the apc extension is present and loaded on the system.
+ * This driver is available iff the apc extension is present and loaded on the system.
*
* @return bool
*/
View
77 src/Stash/Driver/BlackHole.php
@@ -0,0 +1,77 @@
+<?php
+
+/*
+ * This file is part of the Stash package.
+*
+* (c) Robert Hafner <tedivm@tedivm.com>
+*
+* For the full copyright and license information, please view the LICENSE
+* file that was distributed with this source code.
+*/
+
+namespace Stash\Driver;
+
+/**
+ * This class provides a NULL caching driver, it always takes values, but never saves them
+ * Can be used as an default save driver
+ *
+ * @author Benjamin Zikarsky <benjamin.zikarsky@perbility.de>
+ */
+class BlackHole implements DriverInterface
+{
+
+ /**
+ * NOOP constructor
+ */
+ public function __construct(array $options = array())
+ {
+ // empty
+ }
+
+
+ /*
+ * (non-PHPdoc)
+ * @see \Stash\Driver\DriverInterface::clear()
+ */
+ public function clear($key = null)
+ {
+ return true;
+ }
+
+ /*
+ * (non-PHPdoc)
+ * @see \Stash\Driver\DriverInterface::getData()
+ */
+ public function getData($key)
+ {
+ return false;
+ }
+
+ /*
+ * (non-PHPdoc)
+ * @see \Stash\Driver\DriverInterface::purge()
+ */
+ public function purge()
+ {
+ return true;
+ }
+
+ /*
+ * (non-PHPdoc)
+ * @see \Stash\Driver\DriverInterface::storeData()
+ */
+ public function storeData($key, $data, $expiration)
+ {
+ return true;
+ }
+
+ /*
+ * (non-PHPdoc)
+ * @see \Stash\Driver\DriverInterface::isAvailable()
+ */
+ public static function isAvailable()
+ {
+ return true;
+ }
+
+}
View
66 src/Stash/Handler/MultiHandler.php → src/Stash/Driver/Composite.php
@@ -9,51 +9,51 @@
* file that was distributed with this source code.
*/
-namespace Stash\Handler;
+namespace Stash\Driver;
use Stash;
use Stash\Exception\InvalidArgumentException;
use Stash\Exception\RuntimeException;
/**
- * StashMultieHandler is a wrapper around one or more StashHandlers, allowing faster caching engines with size or
- * persistance limitations to be backed up by slower but larger and more persistant caches. There are no artificial
- * limits placed on how many handlers can be staggered.
+ * Composite is a wrapper around one or more StashDrivers, allowing faster caching engines with size or
+ * persistence limitations to be backed up by slower but larger and more persistent caches. There are no artificial
+ * limits placed on how many drivers can be staggered.
*
* @package Stash
* @author Robert Hafner <tedivm@tedivm.com>
*/
-class MultiHandler implements HandlerInterface
+class Composite implements DriverInterface
{
- protected $handlers = array();
+ protected $drivers = array();
/**
- * This function should takes an array which is used to pass option values to the handler.
+ * This function should takes an array which is used to pass option values to the driver.
*
* @param array $options
*/
public function __construct(array $options = array())
{
- if (!isset($options['handlers']) || !is_array($options['handlers']) || count($options['handlers']) < 1) {
- throw new RuntimeException('One or more secondary handlers are required.');
+ if (!isset($options['drivers']) || !is_array($options['drivers']) || count($options['drivers']) < 1) {
+ throw new RuntimeException('One or more secondary drivers are required.');
}
- foreach ($options['handlers'] as $handler) {
- if (!(is_object($handler) && $handler instanceof HandlerInterface)) {
+ foreach ($options['drivers'] as $driver) {
+ if (!(is_object($driver) && $driver instanceof DriverInterface)) {
continue;
}
- $this->handlers[] = $handler;
+ $this->drivers[] = $driver;
}
- if (count($this->handlers) < 1) {
- throw new RuntimeException('None of the secondary handlers can be enabled.');
+ if (count($this->drivers) < 1) {
+ throw new RuntimeException('None of the secondary drivers can be enabled.');
}
}
/**
- * Empty destructor to maintain a standardized interface across all handlers.
+ * Empty destructor to maintain a standardized interface across all drivers.
*
*/
public function __destruct()
@@ -70,18 +70,18 @@ public function __destruct()
*/
public function getData($key)
{
- $failedHandlers = array();
+ $failedDrivers = array();
$return = false;
- foreach ($this->handlers as $handler) {
- if ($return = $handler->getData($key)) {
- $failedHandlers = array_reverse($failedHandlers);
- foreach ($failedHandlers as $failedHandler) {
- $failedHandler->storeData($key, $return['data'], $return['expiration']);
+ foreach ($this->drivers as $driver) {
+ if ($return = $driver->getData($key)) {
+ $failedDrivers = array_reverse($failedDrivers);
+ foreach ($failedDrivers as $failedDriver) {
+ $failedDriver->storeData($key, $return['data'], $return['expiration']);
}
break;
} else {
- $failedHandlers[] = $handler;
+ $failedDrivers[] = $driver;
}
}
@@ -101,10 +101,10 @@ public function getData($key)
*/
public function storeData($key, $data, $expiration)
{
- $handlers = array_reverse($this->handlers);
+ $drivers = array_reverse($this->drivers);
$return = true;
- foreach ($handlers as $handler) {
- $storeResults = $handler->storeData($key, $data, $expiration);
+ foreach ($drivers as $driver) {
+ $storeResults = $driver->storeData($key, $data, $expiration);
$return = $return && $storeResults;
}
@@ -120,10 +120,10 @@ public function storeData($key, $data, $expiration)
*/
public function clear($key = null)
{
- $handlers = array_reverse($this->handlers);
+ $drivers = array_reverse($this->drivers);
$return = true;
- foreach ($handlers as $handler) {
- $clearResults = $handler->clear($key);
+ foreach ($drivers as $driver) {
+ $clearResults = $driver->clear($key);
$return = $return && $clearResults;
}
@@ -137,19 +137,19 @@ public function clear($key = null)
*/
public function purge()
{
- $handlers = array_reverse($this->handlers);
+ $drivers = array_reverse($this->drivers);
$return = true;
- foreach ($handlers as $handler) {
- $purgeResults = $handler->purge();
+ foreach ($drivers as $driver) {
+ $purgeResults = $driver->purge();
$return = $return && $purgeResults;
}
return $return;
}
/**
- * This function checks to see if this handler is available. This always returns true because this
- * handler has no dependencies, beign a wrapper around other classes.
+ * This function checks to see if this driver is available. This always returns true because this
+ * driver has no dependencies, begin a wrapper around other classes.
*
* @return bool true
*/
View
32 src/Stash/Handler/HandlerInterface.php → src/Stash/Driver/DriverInterface.php
@@ -9,28 +9,28 @@
* file that was distributed with this source code.
*/
-namespace Stash\Handler;
+namespace Stash\Driver;
/**
- * Stash Handlers are the engines behind the Stash library. These classes handle the low level operations- retrieving,
- * storing and deleting items in the persistant cache pool. By creating new handlers developers can add new caching
+ * Stash Drivers are the engines behind the Stash library. These classes handle the low level operations- retrieving,
+ * storing and deleting items in the persistant cache pool. By creating new drivers developers can add new caching
* methods to their applications with extremely minimal changes to their existing code base. This interface defines the
- * standard for those handlers and all of them are required to implement it. When writing new cache storage engines this
+ * standard for those drivers and all of them are required to implement it. When writing new cache storage engines this
* is the place to start.
*
* A few important notes when implementing this interface-
*
- * * Unlike with the Stash class itself, instances of handlers are meant to be reused over and over again, allowing them
- * to avoid the overhead of repeadtedly opening and closing resources. There are times when multiple instances of an
+ * * Unlike with the Stash class itself, instances of drivers are meant to be reused over and over again, allowing them
+ * to avoid the overhead of repeatedly opening and closing resources. There are times when multiple instances of an
* engine will be created though (where a developer wants two separate cache pools for example) so static caching
- * techniques should be avoided- the StashHandler will be kept open and reused by the developers, so instance properties
+ * techniques should be avoided- the StashDriver will be kept open and reused by the developers, so instance properties
* will persist in a useful way.
*
* * Each storage engine must be able to handle multiple requests with the same object, meaning functions like
- * getData can be called multiple times in sequence while storeData may be mixed in at random frequences, all using
+ * getData can be called multiple times in sequence while storeData may be mixed in at random frequencies, all using
* different keys.
*
- * * Keys are passed as arrays that represent a hierarchal 'location' where the cached data is virtually stored, with
+ * * Keys are passed as arrays that represent a hierarchical 'location' where the cached data is virtually stored, with
* each item in the array being a deeper level of that hierarchy. In other words $key[0] is the root of the cache tree
* and $key[2] is the child of $key[0] + $key[1]. Each level can be both a piece of data and a parent location, which
* is particularly important for purge and delete operations.
@@ -40,10 +40,10 @@
* @author Robert Hafner <tedivm@tedivm.com>
*/
-interface HandlerInterface
+interface DriverInterface
{
/**
- * Takes an array which is used to pass option values to the handler. As this is the only required function that is
+ * Takes an array which is used to pass option values to the driver. As this is the only required function that is
* used specifically by the developer is is where any engine specific options should go. An engine that requires
* authentication information, as an example, should get them here.
*
@@ -65,11 +65,11 @@ public function getData($key);
* Takes in data from the exposed Stash class and stored it for later retrieval.
*
* *The first argument is an array which should map to a specific, unique location for that array, This location
- * should also be able to handle recursive deletes, where the removal of an item represented by an identicle, but
+ * should also be able to handle recursive deletes, where the removal of an item represented by an identical, but
* truncated, key causes all of the 'children' keys to be removed.
*
* *The second argument is the data itself. This is an array which contains the raw storage as well as meta data
- * about the data. The meta data can be ignored or used by the handler but entire data parameter must be retrievable
+ * about the data. The meta data can be ignored or used by the driver but entire data parameter must be retrievable
* exactly as it was placed in.
*
* *The third parameter is the expiration date of the item as a timestamp. This should also be stored, as it is
@@ -92,7 +92,7 @@ public function storeData($key, $data, $expiration);
public function clear($key = null);
/**
- * Removed any expired code from the cache. For same handlers this can just return true, as their underlying engines
+ * Removed any expired code from the cache. For same drivers this can just return true, as their underlying engines
* automatically take care of time based expiration (apc or memcache for example). This function should also be used
* for other clean up operations that the specific engine needs to handle. This function is generally called outside
* of user requests as part of a maintenance check, so it is okay if the code in this function takes some time to
@@ -103,9 +103,9 @@ public function clear($key = null);
public function purge();
/**
- * Returns whether the handler is able to run in the current environment or not. Any system checks - such as making
+ * Returns whether the driver is able to run in the current environment or not. Any system checks - such as making
* sure any required extensions are missing - should be done here. This is a general check; if any instance of this
- * handler can be used in the current environment it should return true.
+ * driver can be used in the current environment it should return true.
*
* @return bool
*/
View
6 src/Stash/Handler/Ephemeral.php → src/Stash/Driver/Ephemeral.php
@@ -9,18 +9,18 @@
* file that was distributed with this source code.
*/
-namespace Stash\Handler;
+namespace Stash\Driver;
use Stash;
/**
- * The ephemeral class exists to assist with testing the main Stash class. Since this is a very mininal handler we can
+ * The ephemeral class exists to assist with testing the main Stash class. Since this is a very minimal driver we can
* test Stash without having to worry about underlying problems interfering.
*
* @package Stash
* @author Robert Hafner <tedivm@tedivm.com>
*/
-class Ephemeral implements HandlerInterface
+class Ephemeral implements DriverInterface
{
protected $store = array();
View
15 src/Stash/Handler/FileSystem.php → src/Stash/Driver/FileSystem.php
@@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/
-namespace Stash\Handler;
+namespace Stash\Driver;
use Stash;
use Stash\Exception\LogicException;
@@ -24,7 +24,7 @@
* @package Stash
* @author Robert Hafner <tedivm@tedivm.com>
*/
-class FileSystem implements HandlerInterface
+class FileSystem implements DriverInterface
{
/**
* This is the path to the file which will be used to store the cached item. It is based off of the key.
@@ -42,7 +42,7 @@ class FileSystem implements HandlerInterface
/**
* This function stores the path information generated by the makePath function so that it does not have to be
- * calculated each time the handler is called. This only stores path information, it does not store the data to be
+ * calculated each time the driver is called. This only stores path information, it does not store the data to be
* cached
*
* @var array
@@ -97,7 +97,7 @@ public function __construct(array $options = array())
}
/**
- * Empty destructor to maintain a standardized interface across all handlers.
+ * Empty destructor to maintain a standardized interface across all drivers.
*
*/
public function __destruct()
@@ -115,7 +115,7 @@ protected function makeKeyString($key)
/**
* This function retrieves the data from the file. If the file doesn't exist, or is currently being written to, it
- * will return false. If the file is already being written to, this instance of the handler gets disabled so as not
+ * will return false. If the file is already being written to, this instance of the driver gets disabled so as not
* to have a bunch of writes get queued up when a cache item fails to hit.
*
* @return bool
@@ -197,6 +197,7 @@ protected function encode($data)
case 'string':
$dataString = sprintf('"%s"', addcslashes($data, "\t\"\$\\"));
+ break;
case 'none':
default :
@@ -364,8 +365,8 @@ protected function checkFileSystemPermissions()
}
/**
- * This function checks to see if it is possible to enable this handler. This returns true no matter what, since
- * this is the handler of last resort.
+ * This function checks to see if it is possible to enable this driver. This returns true no matter what, since
+ * this is the driver of last resort.
*
* @return bool true
*/
View
16 src/Stash/Handler/Memcache.php → src/Stash/Driver/Memcache.php
@@ -9,12 +9,12 @@
* file that was distributed with this source code.
*/
-namespace Stash\Handler;
+namespace Stash\Driver;
use Stash;
use Stash\Exception\RuntimeException;
-use Stash\Handler\Sub\Memcache as SubMemcache;
-use Stash\Handler\Sub\Memcached as SubMemcached;
+use Stash\Driver\Sub\Memcache as SubMemcache;
+use Stash\Driver\Sub\Memcached as SubMemcached;
/**
* Memcache is a wrapper around the popular memcache server. Memcache supports both memcache php
@@ -23,10 +23,10 @@
* @package Stash
* @author Robert Hafner <tedivm@tedivm.com>
*/
-class Memcache implements HandlerInterface
+class Memcache implements DriverInterface
{
/**
- * Memcache subhandler used by this class.
+ * Memcache subdriver used by this class.
*
* @var SubMemcache|SubMemcached
*/
@@ -42,8 +42,8 @@ class Memcache implements HandlerInterface
* * extension - Which php extension to use, either 'memcache' or 'memcache'. Defaults to memcache with memcache
* as a fallback.
*
- * * Options can be passed to the "memcache" handler by adding them to the options array. The memcache extension
- * defined options using contants, ie Memcached::OPT_*. By passing in the * portion ('compression' for
+ * * Options can be passed to the "memcache" driver by adding them to the options array. The memcache extension
+ * defined options using constants, ie Memcached::OPT_*. By passing in the * portion ('compression' for
* Memcached::OPT_COMPRESSION) and its respective option. Please see the php manual for the specific options
* (http://us2.php.net/manual/en/memcache.constants.php)
*
@@ -79,7 +79,7 @@ public function __construct(array $options = array())
}
/**
- * Empty destructor to maintain a standardized interface across all handlers.
+ * Empty destructor to maintain a standardized interface across all drivers.
*
*/
public function __destruct()
View
100 src/Stash/Handler/Sqlite.php → src/Stash/Driver/Sqlite.php
@@ -9,36 +9,36 @@
* file that was distributed with this source code.
*/
-namespace Stash\Handler;
+namespace Stash\Driver;
use Stash;
use Stash\Exception\RuntimeException;
use Stash\Exception\InvalidArgumentException;
/**
* StashSqlite is a wrapper around one or more SQLite databases stored on the local system. While not as quick at at
- * reading as the StashFilesystem handler this class is signifigantly better when it comes to clearing multiple keys
+ * reading as the StashFilesystem driver this class is significantly better when it comes to clearing multiple keys
* at once.
*
* @package Stash
* @author Robert Hafner <tedivm@tedivm.com>
*/
-class Sqlite implements HandlerInterface
+class Sqlite implements DriverInterface
{
protected $defaultOptions = array('filePermissions' => 0660,
'dirPermissions' => 0770,
'busyTimeout' => 500,
'nesting' => 0,
- 'subhandler' => 'PDO'
+ 'subdriver' => 'PDO'
);
protected $filePerms;
protected $dirPerms;
protected $busyTimeout;
protected $path;
- protected $handlerClass;
+ protected $driverClass;
protected $nesting;
- protected $subHandlers;
+ protected $subDrivers;
protected $disabled = false;
@@ -58,30 +58,30 @@ public function __construct(array $options = array())
$extension = isset($options['extension']) ? strtolower($options['extension']) : 'any';
$version = isset($options['version']) ? $options['version'] : 'any';
- $subhandlers = array();
+ $subdrivers = array();
if(Sub\SqlitePdo::isAvailable()) {
- $subhandlers['pdo'] = '\Stash\Handler\Sub\SqlitePdo';
+ $subdrivers['pdo'] = '\Stash\Driver\Sub\SqlitePdo';
}
if(Sub\Sqlite::isAvailable()) {
- $subhandlers['sqlite'] = '\Stash\Handler\Sub\Sqlite';
+ $subdrivers['sqlite'] = '\Stash\Driver\Sub\Sqlite';
}
if(Sub\SqlitePdo2::isAvailable()) {
- $subhandlers['pdo2'] = '\Stash\Handler\Sub\SqlitePdo2';
+ $subdrivers['pdo2'] = '\Stash\Driver\Sub\SqlitePdo2';
}
- if($extension == 'pdo' && $version != '2' && isset($subhandlers['pdo'])) {
- $handler = $subhandlers['pdo'];
- } elseif($extension == 'sqlite' && isset($subhandlers['sqlite'])) {
- $handler = $subhandlers['sqlite'];
- } elseif($extension == 'pdo' && $version != '3' && isset($subhandlers['pdo2'])) {
- $handler = $subhandlers['pdo2'];
- } elseif(count($subhandlers) > 0 && $extension == 'any') {
- $handler = reset($subhandlers);
+ if($extension == 'pdo' && $version != '2' && isset($subdrivers['pdo'])) {
+ $driver = $subdrivers['pdo'];
+ } elseif($extension == 'sqlite' && isset($subdrivers['sqlite'])) {
+ $driver = $subdrivers['sqlite'];
+ } elseif($extension == 'pdo' && $version != '3' && isset($subdrivers['pdo2'])) {
+ $driver = $subdrivers['pdo2'];
+ } elseif(count($subdrivers) > 0 && $extension == 'any') {
+ $driver = reset($subdrivers);
} else {
throw new RuntimeException('No sqlite extension available.');
}
- $this->handlerClass = $handler;
+ $this->driverClass = $driver;
$this->filePerms = $options['filePermissions'];
$this->dirPerms = $options['dirPermissions'];
$this->busyTimeout = $options['busyTimeout'];
@@ -96,13 +96,13 @@ public function __construct(array $options = array())
*/
public function getData($key)
{
- if (!($sqlHandler = $this->getSqliteHandler($key))) {
+ if (!($sqlDriver = $this->getSqliteDriver($key))) {
return false;
}
$sqlKey = $this->makeSqlKey($key);
- if (!($data = $sqlHandler->get($sqlKey))) {
+ if (!($data = $sqlDriver->get($sqlKey))) {
return false;
}
@@ -119,7 +119,7 @@ public function getData($key)
*/
public function storeData($key, $data, $expiration)
{
- if (!($sqlHandler = $this->getSqliteHandler($key))) {
+ if (!($sqlDriver = $this->getSqliteDriver($key))) {
return false;
}
@@ -128,7 +128,7 @@ public function storeData($key, $data, $expiration)
'encoding' => \Stash\Utilities::encoding($data)
);
- return $sqlHandler->set($this->makeSqlKey($key), $storeData, $expiration);
+ return $sqlDriver->set($this->makeSqlKey($key), $storeData, $expiration);
}
/**
@@ -147,15 +147,15 @@ public function clear($key = null)
}
foreach ($databases as $database) {
- if (!($handler = $this->getSqliteHandler($database, true))) {
+ if (!($driver = $this->getSqliteDriver($database, true))) {
continue;
}
- isset($sqlKey) ? $handler->clear($sqlKey) : $handler->clear();
- $handler->__destruct();
- unset($handler);
+ isset($sqlKey) ? $driver->clear($sqlKey) : $driver->clear();
+ $driver->__destruct();
+ unset($driver);
}
- $this->subHandlers = array();
+ $this->subDrivers = array();
return true;
}
@@ -172,8 +172,8 @@ public function purge()
$expiration = time();
foreach ($databases as $database) {
- if ($handler = $this->getSqliteHandler($database, true)) {
- $handler->purge();
+ if ($driver = $this->getSqliteDriver($database, true)) {
+ $driver->purge();
}
}
return true;
@@ -183,9 +183,9 @@ public function purge()
*
* @param null|array $key
* @param bool $name = false
- * @return \Stash\Handler\Sub\Sqlite
+ * @return \Stash\Driver\Sub\Sqlite
*/
- protected function getSqliteHandler($key, $name = false)
+ protected function getSqliteDriver($key, $name = false)
{
if ($name) {
if (!is_scalar($key)) {
@@ -210,31 +210,31 @@ protected function getSqliteHandler($key, $name = false)
$file = $this->path . rtrim($fileName, '_') . '.sqlite';
}
- if (isset($this->subHandlers[$file])) {
- return $this->subHandlers[$file];
+ if (isset($this->subDrivers[$file])) {
+ return $this->subDrivers[$file];
}
- $handlerClass = $this->handlerClass;
+ $driverClass = $this->driverClass;
- if(is_null($handlerClass))
+ if(is_null($driverClass))
return false;
- $handler = new $handlerClass($file, $this->dirPerms, $this->filePerms, $this->busyTimeout);
+ $driver = new $driverClass($file, $this->dirPerms, $this->filePerms, $this->busyTimeout);
- $this->subHandlers[$file] = $handler;
- return $handler;
+ $this->subDrivers[$file] = $driver;
+ return $driver;
}
/**
- * Destroys the sub-handlers when this handler is unset -- required for Windows compatibility.
+ * Destroys the sub-drivers when this driver is unset -- required for Windows compatibility.
*
*/
public function __destruct()
{
- if ($this->subHandlers) {
- foreach ($this->subHandlers as &$handler) {
- $handler->__destruct();
- unset($handler);
+ if ($this->subDrivers) {
+ foreach ($this->subDrivers as &$driver) {
+ $driver->__destruct();
+ unset($driver);
}
}
}
@@ -275,7 +275,7 @@ protected function checkFileSystemPermissions()
}
/**
- * Checks availability of the specified subhandler.
+ * Checks availability of the specified subdriver.
*
* @return bool
*/
@@ -285,17 +285,17 @@ protected function checkStatus()
throw new RuntimeException('No Sqlite extension is available.');
}
- $handler = $this->getSqliteHandler(array('_none'));
+ $driver = $this->getSqliteDriver(array('_none'));
- if(!$handler) {
- throw new RuntimeException('No Sqlite handler could be loaded.');
+ if(!$driver) {
+ throw new RuntimeException('No Sqlite driver could be loaded.');
}
- $handler->checkFileSystemPermissions();
+ $driver->checkFileSystemPermissions();
}
/**
- * Returns whether the handler is able to run in the current environment or not. Any system checks- such as making
+ * Returns whether the driver is able to run in the current environment or not. Any system checks- such as making
* sure any required extensions are missing- should be done here.
*
* @return bool
View
2 src/Stash/Handler/Sub/Memcache.php → src/Stash/Driver/Sub/Memcache.php
@@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/
-namespace Stash\Handler\Sub;
+namespace Stash\Driver\Sub;
use Stash\Exception\RuntimeException;
View
2 src/Stash/Handler/Sub/Memcached.php → src/Stash/Driver/Sub/Memcached.php
@@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/
-namespace Stash\Handler\Sub;
+namespace Stash\Driver\Sub;
use Stash\Exception\MemcacheException;
use Stash\Exception\RuntimeException;
View
52 src/Stash/Handler/Sub/Sqlite.php → src/Stash/Driver/Sub/Sqlite.php
@@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/
-namespace Stash\Handler\Sub;
+namespace Stash\Driver\Sub;
use Stash\Exception\RuntimeException;
use Stash\Exception\InvalidArgumentException;
@@ -21,7 +21,7 @@
class Sqlite
{
protected $path;
- protected $handler;
+ protected $driver;
protected $creationSql = 'CREATE TABLE cacheStore (
key TEXT UNIQUE ON CONFLICT REPLACE,
@@ -37,27 +37,27 @@ class Sqlite
protected $busyTimeout;
protected $responseCode;
- public function __construct($path, $directoryPermissiom, $filePermission, $busyTimeout)
+ public function __construct($path, $directoryPermission, $filePermission, $busyTimeout)
{
$this->path = $path;
$this->filePermissions = $filePermission;
- $this->dirPermissions = $directoryPermissiom;
+ $this->dirPermissions = $directoryPermission;
$this->busyTimeout = $busyTimeout;
$this->responseCode = 1; // SQLITE_ASSOC
}
public function __destruct()
{
- unset($this->handler);
+ unset($this->driver);
}
public function get($key)
{
- if (!($handler = $this->getHandler())) {
+ if (!($driver = $this->getDriver())) {
return false;
}
- $query = $handler->query("SELECT * FROM cacheStore WHERE key LIKE '{$key}'");
+ $query = $driver->query("SELECT * FROM cacheStore WHERE key LIKE '{$key}'");
if ($query === false) {
return false;
}
@@ -71,7 +71,7 @@ public function get($key)
public function set($key, $value, $expiration)
{
- if (!($handler = $this->getHandler())) {
+ if (!($driver = $this->getDriver())) {
return false;
}
@@ -84,7 +84,7 @@ public function set($key, $value, $expiration)
$this->setTimeout($this->busyTimeout * (ceil($contentLength / 100000))); // .5s per 100k
}
- $query = $handler->query("INSERT INTO cacheStore (key, expiration, data)
+ $query = $driver->query("INSERT INTO cacheStore (key, expiration, data)
VALUES ('{$key}', '{$expiration}', '{$data}')");
return true;
@@ -93,29 +93,29 @@ public function set($key, $value, $expiration)
public function clear($key = null)
{
// return true if the cache is already empty
- if (!($handler = $this->getHandler())) {
+ if (!($driver = $this->getDriver())) {
return true;
}
if (!isset($key)) {
- unset($handler);
- unset($this->handler);
- $this->handler = false;
+ unset($driver);
+ unset($this->driver);
+ $this->driver = false;
\Stash\Utilities::deleteRecursive($this->path);
} else {
- $query = $handler->query("DELETE FROM cacheStore WHERE key LIKE '{$key}%'");
+ $query = $driver->query("DELETE FROM cacheStore WHERE key LIKE '{$key}%'");
}
return true;
}
public function purge()
{
- if (!($handler = $this->getHandler())) {
+ if (!($driver = $this->getDriver())) {
return false;
}
- $handler->query('DELETE FROM cacheStore WHERE expiration < ' . time());
- $handler->query('VACUUM');
+ $driver->query('DELETE FROM cacheStore WHERE expiration < ' . time());
+ $driver->query('VACUUM');
return true;
}
@@ -137,16 +137,16 @@ static public function isAvailable()
protected function setTimeout($milliseconds)
{
- if (!($handler = $this->getHandler())) {
+ if (!($driver = $this->getDriver())) {
return false;
}
- $handler->busyTimeout($milliseconds);
+ $driver->busyTimeout($milliseconds);
}
- protected function getHandler()
+ protected function getDriver()
{
- if (isset($this->handler) && $this->handler !== false) {
- return $this->handler;
+ if (isset($this->driver) && $this->driver !== false) {
+ return $this->driver;
}
if (!file_exists($this->path)) {
@@ -177,21 +177,21 @@ protected function getHandler()
$runInstall = false;
}
- $db = $this->buildHandler();
+ $db = $this->buildDriver();
if ($runInstall && !$db->query($this->creationSql)) {
- unlink($path);
+ unlink($this->path);
throw new RuntimeException('Unable to set SQLite: structure');
}
- $this->handler = $db;
+ $this->driver = $db;
// prevent the cache from getting hungup waiting on a return
$this->setTimeout($this->busyTimeout);
return $db;
}
- protected function buildHandler()
+ protected function buildDriver()
{
if (!$db = new \SQLiteDatabase($this->path, $this->filePermissions, $errorMessage)) {
throw new RuntimeException('Unable to open SQLite Database: ' . $errorMessage);
View
12 src/Stash/Handler/Sub/SqlitePdo.php → src/Stash/Driver/Sub/SqlitePdo.php
@@ -9,19 +9,19 @@
* file that was distributed with this source code.
*/
-namespace Stash\Handler\Sub;
+namespace Stash\Driver\Sub;
/**
* @package Stash
* @author Robert Hafner <tedivm@tedivm.com>
*/
class SqlitePdo extends Sqlite
{
- public function __construct($path, $directoryPermissiom, $filePermission, $busyTimeout)
+ public function __construct($path, $directoryPermission, $filePermission, $busyTimeout)
{
$this->path = $path;
$this->filePermissions = $filePermission;
- $this->dirPermissions = $directoryPermissiom;
+ $this->dirPermissions = $directoryPermission;
$this->busyTimeout = $busyTimeout;
$this->responseCode = \PDO::FETCH_ASSOC;
}
@@ -34,15 +34,15 @@ static public function isAvailable()
protected function setTimeout($milliseconds)
{
- if (!($handler = $this->getHandler())) {
+ if (!($driver = $this->getDriver())) {
return false;
}
$timeout = ceil($milliseconds / 1000);
- $handler->setAttribute(\PDO::ATTR_TIMEOUT, $timeout);
+ $driver->setAttribute(\PDO::ATTR_TIMEOUT, $timeout);
}
- protected function buildHandler()
+ protected function buildDriver()
{
$db = new \PDO('sqlite:' . $this->path);
return $db;
View
4 src/Stash/Handler/Sub/SqlitePdo2.php → src/Stash/Driver/Sub/SqlitePdo2.php
@@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/
-namespace Stash\Handler\Sub;
+namespace Stash\Driver\Sub;
/**
* @package Stash
@@ -23,7 +23,7 @@ static public function isAvailable()
return in_array('sqlite2', $drivers);
}
- protected function buildHandler()
+ protected function buildDriver()
{
$db = new \PDO('sqlite2:' . $this->path);
return $db;
View
10 src/Stash/Handler/Xcache.php → src/Stash/Driver/Xcache.php
@@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/
-namespace Stash\Handler;
+namespace Stash\Driver;
use Stash;
use Stash\Exception\RuntimeException;
@@ -22,7 +22,7 @@
*
* @codeCoverageIgnore Just until I figure out how to get phpunit working over http, or xcache over cli
*/
-class Xcache implements HandlerInterface
+class Xcache implements DriverInterface
{
protected $ttl = 300;
protected $user;
@@ -48,7 +48,7 @@ public function __construct(array $options = array())
}
/**
- * Empty destructor to maintain a standardized interface across all handlers.
+ * Empty destructor to maintain a standardized interface across all drivers.
*
*/
public function __destruct()
@@ -81,7 +81,7 @@ public function getData($key)
/**
* This function takes an array as its first argument and the expiration time as the second. This array contains two
* items, "createdOn" describing the first time the item was called and "return", which is the data that needs to be
- * stored. This function needs to store that data in such a way that it can be retrieced exactly as it was sent. The
+ * stored. This function needs to store that data in such a way that it can be retrieved exactly as it was sent. The
* expiration time needs to be stored with this data.
*
* @param array $data
@@ -190,7 +190,7 @@ public function purge()
}
/**
- * This function checks to see if it is possible to enable this handler.
+ * This function checks to see if it is possible to enable this driver.
*
* @return bool true
*/
View
80 src/Stash/Drivers.php
@@ -0,0 +1,80 @@
+<?php
+
+/*
+ * This file is part of the Stash package.
+ *
+ * (c) Robert Hafner <tedivm@tedivm.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Stash;
+
+/**
+ * Drivers contains various functions used to organize Driver classes that are available in the system.
+ *
+ * @package Stash
+ * @author Robert Hafner <tedivm@tedivm.com>
+ */
+class Drivers
+{
+ /**
+ * An array of possible cache storage data methods, with the driver class as the array value.
+ *
+ * @var array
+ */
+ protected static $drivers = array('Apc' => '\Stash\Driver\Apc',
+ 'Ephemeral' => '\Stash\Driver\Ephemeral',
+ 'FileSystem' => '\Stash\Driver\FileSystem',
+ 'Memcache' => '\Stash\Driver\Memcache',
+ 'Composite' => '\Stash\Driver\Composite',
+ 'SQLite' => '\Stash\Driver\Sqlite',
+ 'Xcache' => '\Stash\Driver\Xcache',
+ );
+
+
+ /**
+ * Returns a list of build-in cache drivers that are also supported by this system.
+ *
+ * @return array Driver Name => Class Name
+ */
+ static function getDrivers()
+ {
+ $availableDrivers = array();
+ foreach (self::$drivers as $name => $class) {
+ if (!class_exists($class)) {
+ continue;
+ }
+
+ if (!in_array('Stash\Driver\DriverInterface', class_implements($class))) {
+ continue;
+ }
+
+ if($name == 'MultiDriver') {
+ $availableDrivers[$name] = $class;
+ } else {
+ if($class::isAvailable()) {
+ $availableDrivers[$name] = $class;
+ }
+ }
+ }
+
+ return $availableDrivers;
+ }
+
+ static function registerDriver($name, $class)
+ {
+ self::$drivers[$name] = $class;
+ }
+
+ static function getDriverClass($name)
+ {
+ if (!isset(self::$drivers[$name])) {
+ return false;
+ }
+
+ return self::$drivers[$name];
+ }
+
+}
View
79 src/Stash/Handlers.php
@@ -1,79 +0,0 @@
-<?php
-
-/*
- * This file is part of the Stash package.
- *
- * (c) Robert Hafner <tedivm@tedivm.com>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Stash;
-
-/**
- * Handlers contains various functions used to organize Handler classes that are available in the system.
- *
- * @package Stash
- * @author Robert Hafner <tedivm@tedivm.com>
- */
-class Handlers
-{
- /**
- * An array of possible cache storage data methods, with the handler class as the array value.
- *
- * @var array
- */
- protected static $handlers = array('Apc' => '\Stash\Handler\Apc',
- 'FileSystem' => '\Stash\Handler\FileSystem',
- 'Memcached' => '\Stash\Handler\Memcached',
- 'MultiHandler' => '\Stash\Handler\MultiHandler',
- 'SQLite' => '\Stash\Handler\Sqlite',
- 'Xcache' => '\Stash\Handler\Xcache',
- );
-
-
- /**
- * Returns a list of build-in cache handlers that are also supported by this system.
- *
- * @return array Handler Name => Class Name
- */
- static function getHandlers()
- {
- $availableHandlers = array();
- foreach (self::$handlers as $name => $class) {
- if (!class_exists($class)) {
- continue;
- }
-
- if (!in_array('Stash\Handler\HandlerInterface', class_implements($class))) {
- continue;
- }
-
- if($name == 'MultiHandler') {
- $availableHandlers[$name] = $class;
- } else {
- if($class::isAvailable()) {
- $availableHandlers[$name] = $class;
- }
- }
- }
-
- return $availableHandlers;
- }
-
- static function registerHandler($name, $class)
- {
- self::$handlers[$name] = $class;
- }
-
- static function getHandlerClass($name)
- {
- if (!isset(self::$handlers[$name])) {
- return false;
- }
-
- return self::$handlers[$name];
- }
-
-}
View
275 src/Stash/Cache.php → src/Stash/Item.php
@@ -11,7 +11,7 @@
namespace Stash;
-use Stash\Handler\HandlerInterface;
+use Stash\Driver\DriverInterface;
use Stash\Exception\Exception;
use Stash\Exception\InvalidArgumentException;
@@ -20,111 +20,10 @@
* connection. This class can store any native php datatype, as long as it can be serialized (so when creating classes
* that you wish to store instances of, remember the __sleep and __wake magic functions).
*
- * * * * * * * * * * * *
- * Creating Stash Object
- * * *
- *
- * <code>
- * // Create backend handler
- * $handler = new Stash\Handler\FileSystem();
- *
- * // Create Stash object and inject handler.
- * $stash = new Stash\Cache($handler);
- *
- * // Setup Key
- * $stash->setupKey('Path', 'To', 'Item');
- * </code>
- *
- * This can also be accomplished using one of the Stash wrappers, like StashBox.
- *
- * * * * * * * *
- * Getting and Storing Data
- * * *
- *
- * <code>
- * // Create backend handler
- * $handler = new Stash\Handler\FileSystem();
- *
- * // Set backend handler - this only has to be done once!
- * Stash\Box::setHandler($handler);
- *
- * // Get Cache object, including optional key.
- * $cache = Stash\Box::getCache('Path', 'To', 'Item');
- *
- * // Get another, new Cache object without having to set a new handler.
- * $otherCache = Stash\Box::getCache('Object', 'Stored');
- * </code>
- *
- * Using Stash is a simple process of getting data, checking if it is stale, and then storing the recalculated data
- * if it was.
- *
- * <code>
- * // Grab a fresh Stash item.
- * $cache = Stash\Box::getCache('path', 'to', 'the','item');
- *
- * // Pull the data from the cache.
- * $data = $cache->get();
- *
- * // Check to see if the data is stale or didn't return at all.
- * if($cache->isMiss())
- * {
- * // Run all the long running code.
- * $data = runExpensiveCode();
- *
- * // Save the code for later.
- * $cache->set($data);
- * }
- * </code>
- *
- * * * * * * * * *
- * Clearing Data
- * * *
- *
- * Clearing data is very similar to getting it.
- * <code>
- * $handler = new Stash\Handler\FileSystem();
- * $cache = new Stash\Cache($handler);
- * $cache->setupKey('path', 'to', item');
- * $cache->clear();
- * </code>
- *
- * The wrappers, like StashBox, offer a one function call to clear data.
- * <code>
- * $cache = Stash\Box::clearCache('path', 'to', 'item');
- *
- * // Clear out everything in the 'path' node, including 'path' and 'path' 'to' 'item'.
- * $cache = Stash\Box::clearCache('path');
- *
- * // Clear out everything in the cache.
- * $cache = Stash\Box::clearCache();
- * </code>
- *
- * * * * * * * *
- * Purging Stale Data
- * * *
- *
- * Running the purge function cleans out any stale data, lowering the size of the cache pool. It also allows the
- * handlers to run their own handler specific cleanup functions. For larger caches this function can take quite a bit
- * of time, so it is best run in its own cleanup process.
- *
- * <code>
- * $handler = new Stash\Handler\FileSystem();
- * $cache = new Stash\Cache($handler);
- * $cache->purge();
- * </code>
- *
- * The wrappers, like Stash\Box, offer a one function call to clear data.
- * <code>
- * Stash\Box::purgeCache();
- * </code>
- *
- *
- *
- *
* @package Stash
* @author Robert Hafner <tedivm@tedivm.com>
*/
-class Cache
+class Item
{
const SP_NONE = 0;
const SP_OLD = 1;
@@ -140,7 +39,7 @@ class Cache
static public $cacheTime = 432000; // five days
/**
- * Disbles the cache system wide. It is used internally when the storage engine fails or if the cache is being
+ * Disables the cache system wide. It is used internally when the storage engine fails or if the cache is being
* cleared. This differs from the cacheEnabled property in that it affects all instances of the cache, not just one.
*
* @var bool
@@ -186,7 +85,7 @@ class Cache
protected $defaults = array('precompute_time' => 40, // time, in seconds, before expiration
'sleep_time' => 500, // time, in microseconds, to sleep
'sleep_attempts' => 1, // number of times to sleep, wake up, and recheck cache
- 'stampede_ttl' => 30, // How long a stampede flag will be aknowledged
+ 'stampede_ttl' => 30, // How long a stampede flag will be acknowledged
);
/**
@@ -211,34 +110,37 @@ class Cache
protected $stampedeRunning = false;
/**
- * The cacheHandler being used by the system. While this class handles all of the higher functions, it's the cache
- * handler here that handles all of the storage/retrieval functionality. This value is set by the constructor.
+ * The cacheDriver being used by the system. While this class handles all of the higher functions, it's the cache
+ * driver here that handles all of the storage/retrieval functionality. This value is set by the constructor.
*
- * @var cacheHandler
+ * @var Stash\Driver\DriverInterface
*/
- protected $handler;
+ protected $driver;
/**
* This is a flag to see if a valid response is returned. It is set by the getData function and is used by the
* isMiss function.
*
* @var bool
*/
- private $isHit = false;
+ private $isHit = null;
/**
- * This constructor requires a StashHandler object.
+ * This constructor is an internal function used by the Pool object when
+ * creating new Item objects. It should not be called directly.
*
- * @param HandlerInterface If no handler is passed the cache is set to script time only.
+ * @internal
+ * @param DriverInterface If no driver is passed the cache is set to script time only.
*/
- public function __construct(HandlerInterface $handler)
+ public function __construct(DriverInterface $driver, $key)
{
- $this->handler = $handler;
+ $this->driver = $driver;
+ $this->setupKey($key);
}
/**
- * Disables the specific instance of the cache handler. This makes it simpler to embed the cache handling code in
- * places where it may not always want the results stored.
+ * This disables any IO operations by this object, effectively preventing
+ * the reading and writing of new data.
*
* @return bool
*/
@@ -249,45 +151,19 @@ public function disable()
}
/**
- * Takes a string or an array that represents the location of a cached item in the cache pool. Keys are considered
- * Stackable, in the sense that keys can be nested inside of other keys (similar to how folders are nested in an
- * filesystem). This nesting can be represented using the slash delimiter ("path/to/item") or by using an array
- * ("array('path', 'to', 'item')").
- *
- * @example $cache = new Cache(array('permissions', 'user', '4', '2')); where 4 is the user id and 2 is the location id.
- * @example $cache = new Cache('permissions/user/' . '4' . '/' '2'); where 4 is the user id and 2 is the location id.
- * @example $cache = new Cache("permissions/user/{$userId}/{$locationId"});
- *
- * @param string|array $key
- */
- public function setupKey($key)
- {
- if (is_array($key)) {
- $this->keyString = implode('/', $key);
- } else {
- $this->keyString = $key;
- $key = trim($key, '/');
- $key = explode('/', $key);
- }
-
- // We implant the namespace "cache" to the front of every stash object's key. This allows us to segment
- // off the user data, and user other 'namespaces' for internal purposes.
- array_unshift($key, 'cache');
- $this->key = array_map('strtolower', $key);
- }
-
- /**
- * Returns the key as a string.
+ * Returns the key as a string. This is particularly useful when the Item is
+ * returned as a group of Items in an Iterator.
*
- * @return string
+ * @return string|bool Returns false if no key is set.
*/
public function getKey()
{
return isset($this->keyString) ? $this->keyString : false;
}
/**
- * Clears the current Stash item and all of its children. If no key is set it clears the entire cache.
+ * Clears the current Item. If hierarchical or "stackable" caching is being
+ * used this function will also remove children Items.
*
* @return bool
*/
@@ -307,38 +183,15 @@ private function executeClear()
return false;
}
- return $this->handler->clear(isset($this->key) ? $this->key : null);
+ return $this->driver->clear(isset($this->key) ? $this->key : null);
}
/**
- * Removes all expired or stale data from the cache system. It may also perform other cleanup actions depending on
- * the cache handler used.
- *
- * @return bool
- */
- public function purge()
- {
- try {
- return $this->executePurge();
- } catch (Exception $e) {
- $this->disable();
- return false;
- }
- }
-
- private function executePurge()
- {
- if ($this->isDisabled()) {
- return false;
- }
-
- return $this->handler->purge();
- }
-
- /**
- * Returns the data retrieved from the cache. Since this can return false or null as a correctly cached value, the
- * return value should not be used to determine successful retrieval of data- for that use the "isMiss()" function
- * after call this one. If no value is stored at all then this function will return null.
+ * Returns the data retrieved from the cache. Since this can return false or
+ * null as a correctly cached value, the return value should not be used to
+ * determine successful retrieval of data- for that use the "isMiss()"
+ * function after call this one. If no value is stored at all then this
+ * function will return null.
*
* @return mixed|null
*/
@@ -356,6 +209,8 @@ private function executeGet($invalidation, $arg, $arg2)
{
self::$cacheCalls++;
+ $this->isHit = false;
+
if ($this->isDisabled()) {
return null;
}
@@ -403,6 +258,9 @@ private function executeGet($invalidation, $arg, $arg2)
*/
public function isMiss()
{
+ if (!isset($this->isHit))
+ $this->get();
+
if ($this->isDisabled()) {
return true;
}
@@ -411,7 +269,8 @@ public function isMiss()
}
/**
- * Enables stampede protection by marking this specific instance of Stash as the one regenerating the cache.
+ * Enables stampede protection by marking this specific instance of the Item
+ * as the one regenerating the cache.
*
* @return bool
*/
@@ -432,21 +291,22 @@ public function lock($ttl = null)
$spkey = $this->key;
$spkey[0] = 'sp';
- return $this->handler->storeData($spkey, true, time() + $expiration);
+ return $this->driver->storeData($spkey, true, time() + $expiration);
}
/**
- * Takes and stores data for later retrieval. This data can be any php data, including arrays and object, except
- * resources and objects which are unable to be serialized.
+ * Takes and stores data for later retrieval. This data can be any php data,
+ * including arrays and object, except resources and objects which are
+ * unable to be serialized.
*
* @param mixed $data bool
- * @param int|DateTime|null $time How long the item should be stored. Int is time (seconds), DateTime a future date
+ * @param int|DateTime|null $ttl Int is time (seconds), DateTime a future expiration date
* @return bool Returns whether the object was successfully stored or not.
*/
- public function set($data, $time = null)
+ public function set($data, $ttl = null)
{
try {
- return $this->executeSet($data, $time);
+ return $this->executeSet($data, $ttl);
} catch (Exception $e) {
$this->disable();
return false;
@@ -488,16 +348,16 @@ private function executeSet($data, $time)
if ($this->stampedeRunning == true) {
$spkey = $this->key;
$spkey[0] = 'sp'; // change "cache" data namespace to stampede namespace
- $this->handler->clear($spkey);
+ $this->driver->clear($spkey);
$this->stampedeRunning = false;
}
- return $this->handler->storeData($this->key, $store, $expiration);
+ return $this->driver->storeData($this->key, $store, $expiration);
}
/**
- * Extends the expiration on the current cached item. For some engines this can be faster than storing the item
- * again.
+ * Extends the expiration on the current cached item. For some engines this
+ * can be faster than storing the item again.
*
* @return bool
*/
@@ -511,14 +371,25 @@ public function extendCache()
}
/**
- * Returns true is another instance of Stash is currently recalculating the cache.
+ * Return true if caching is disabled
+ */
+ public function isDisabled()
+ {
+ return self::$runtimeDisable
+ || !$this->cacheEnabled
+ || (defined('STASH_DISABLE_CACHE') && STASH_DISABLE_CACHE);
+ }
+
+
+ /**
+ * Returns true is another Item is currently recalculating the cache.
*
* @return bool
*/
protected function getStampedeFlag($key)
{
$key[0] = 'sp'; // change "cache" data namespace to stampede namespace
- $spReturn = $this->handler->getData($key);
+ $spReturn = $this->driver->getData($key);
$sp = isset($spReturn['data']) ? $spReturn['data'] : false;
@@ -531,14 +402,14 @@ protected function getStampedeFlag($key)
}
/**
- * Returns the record for the current key, whether that record is pulled from memory or a handler. If there is no
+ * Returns the record for the current key, whether that record is pulled from memory or a driver. If there is no
* record than an empty array is returned.
*
* @return array
*/
protected function getRecord()
{
- $record = $this->handler->getData($this->key);
+ $record = $this->driver->getData($this->key);
if (!is_array($record)) {
return array();
@@ -632,10 +503,26 @@ protected function validateRecord($validation, &$record)
}
/**
- * Return true if caching is disabled
+ * This function is used by the Pool object while creating this object. It
+ * is an internal function an should not be called directly.
+ *
+ * @internal
+ * @param string|array $key
*/
- public function isDisabled()
+ protected function setupKey($key)
{
- return self::$runtimeDisable || !$this->cacheEnabled || (defined('STASH_DISABLE_CACHE') && STASH_DISABLE_CACHE);
+ if (is_array($key)) {
+ $this->keyString = implode('/', $key);
+ } else {
+ $this->keyString = $key;
+ $key = trim($key, '/');
+ $key = explode('/', $key);
+ }
+
+ // We implant the namespace "cache" to the front of every stash object's key. This allows us to segment
+ // off the user data, and user other 'namespaces' for internal purposes.
+ array_unshift($key, 'cache');
+ $this->key = array_map('strtolower', $key);
}
+
}
View
134 src/Stash/Manager.php
@@ -1,134 +0,0 @@
-<?php
-
-/*
- * This file is part of the Stash package.
- *
- * (c) Robert Hafner <tedivm@tedivm.com>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Stash;
-
-use Stash\Handler\HandlerInterface;
-use Stash\Handler\Ephemeral;
-use Stash\Exception\InvalidArgumentException;
-