locomotivemtl / charcoal-cache
Charcoal service provider for the Stash Cache Library
Installs: 10 406
Dependents: 4
Suggesters: 0
Security: 0
Stars: 0
Watchers: 13
Forks: 0
Open Issues: 1
Requires
- php: >=5.6.0 || >=7.0
- locomotivemtl/charcoal-config: ~0.8
- pimple/pimple: ^3.0
- psr/cache: ^1.0
- tedivm/stash: ~0.14
Requires (Dev)
- php-coveralls/php-coveralls: ^2.0
- phpunit/phpunit: ^5.7 || ^6.5
- psr/log: ^1.0
- slim/http: ^0.3 || ^0.4
- squizlabs/php_codesniffer: ^3.0
README
A Charcoal service provider for the Stash Cache Library.
Table of Contents
Installation
-
The preferred (and only supported) method is with Composer:
$ composer require locomotivemtl/charcoal-cache
-
Add the service provider and configure the default caching service via the application configset:
"service_providers": { "charcoal/cache/service-provider/cache": {} }, "cache": { "prefix": "foobar", "types": [ "apc", "memcache", "redis" ] }
or via the service container:
$container->register(new \Charcoal\Cache\ServiceProvider\CacheServiceProvider()); $container['cache/config'] = new \Charcoal\Cache\CacheConfig([ 'prefix' => 'foobar', 'types' => [ 'apc', 'memcache', 'redis' ], ]);
If you are using locomotivemtl/charcoal-app, the CacheServiceProvider
is automatically registered by the AppServiceProvider
.
Dependencies
Required
- PHP 5.6+: PHP 7 is recommended.
- tedivm/stash: PSR-6 compliant caching library.
- pimple/pimple: PSR-11 compliant service container and provider library.
- locomotivemtl/charcoal-config: For configuring the caching service.
PSR
- PSR-3: Common interface for logging libraries. Supported by Stash.
- PSR-6: Common interface for caching libraries. Fulfilled by Stash.
- PSR-7: Common interface for HTTP messages. Followed by
CacheMiddleware
. - PSR-11: Common interface for dependency containers. Fulfilled by Pimple.
Dependents
- locomotivemtl/charcoal-admin: Admin interface for Charcoal applications.
- locomotivemtl/charcoal-app: PSR-7 compliant framework for web applications.
For caching HTTP responses via theCacheMiddleware
. - locomotivemtl/charcoal-core: Collection, model, metadata, and database library.
For caching object data and model metadata.
Service Provider
Parameters
- cache/available-drivers: Collection of registered cache drivers that are supported by this system (via
Stash\DriverList
).
Services
- cache/config: Configuration object for the caching service.
See Pool Configuration for available options. - cache/drivers: Collection of cache driver instances (as a service container) which uses
cache/available-drivers
.
These drivers are pre-configured: - cache/builder: Instance of
CacheBuilder
that is used to build a cache pool. - cache/driver: Reference to the Stash cache driver used by
cache
. Defaults to "memory". - cache: Main instance of the Stash cache pool which uses
cache/driver
andcache/config.prefix
.
Configuration
Pool Configuration
Each pool comes with a set of default options which can be individually overridden.
Driver Configuration
Each driver comes with a set of default options which can be individually overridden.
—N/A—
Usage
Just fetch the default cache pool service:
$pool = $this->container->get('cache');
Or a custom-defined cache pool:
// Create a Stash pool with the Memcached driver and a custom namespace. $pool1 = $this->container->get('cache/builder')->build('memcache', 'altcache'); // Create a custom Stash pool with the FileSystem driver and custom features. $pool2 = $this->container->get('cache/builder')->build('file', [ 'namespace' => 'mycache', 'logger' => $this->container->get('logger.custom_logger'), 'pool_class' => \MyApp\Cache\Pool::class, 'item_class' => \MyApp\Cache\Item::class, ]); // Create a Stash pool with the "memory" cache driver. $pool3 = new \Stash\Pool($container['cache/drivers']['memory']);
Then you can use the cache service directly:
// Get a Stash object from the cache pool. $item = $pool->getItem("/user/{$userId}/info"); // Get the data from it, if any happens to be there. $userInfo = $item->get(); // Check to see if the cache missed, which could mean that it either // didn't exist or was stale. if ($item->isMiss()) { // Run the relatively expensive code. $userInfo = loadUserInfoFromDatabase($userId); // Set the new value in $item. $item->set($userInfo); // Store the expensive code so the next time it doesn't miss. $pool->save($item); } return $userInfo;
See the Stash documentation for more information on using the cache service.
Middleware
The CacheMiddleware
is available for PSR-7 applications that support middleware. The middleware saves the HTTP response body and headers into a PSR-6 cache pool and returns that cached response if still valid.
If you are using locomotivemtl/charcoal-app, you can add the middleware via the application configset:
"middlewares": { "charcoal/cache/middleware/cache": { "active": true, "methods": [ "GET", "HEAD" ] } }
Otherwise, with Slim, for example:
$app = new \Slim\App(); // Register middleware $app->add(new \Charcoal\Cache\Middleware\CacheMiddleware([ 'cache' => new \Stash\Pool(), 'methods' => [ 'GET', 'HEAD' ], ]));
The middleware comes with a set of default options which can be individually overridden.
By Default
All HTTP responses are cached unless:
- the request method is not GET
- the request URI path starts with
/admin…
- the request URI contains a query string
- the response is not OK (200)
Ignoring Query Strings
If query strings don't affect the server's response, you can permit caching of requests by ignoring all query parameters:
"ignored_query": "*"
or some of them:
"ignored_query": [ "sort", "theme" ]
Helpers
CachePoolAwareTrait
The CachePoolAwareTrait
is offered as a convenience to avoid duplicate / boilerplate code. It simply sets and gets an instance of \Psr\Cache\CacheItemPoolInterface
.
Assign a cache pool with setCachePool()
and retrieve it with cachePool()
.
Both methods are protected; this trait has no public interface.
Development
To install the development environment:
$ composer install
To run the scripts (phplint, phpcs, and phpunit):
$ composer test
API Documentation
- The auto-generated
phpDocumentor
API documentation is available at:
https://locomotivemtl.github.io/charcoal-cache/docs/master/ - The auto-generated
apigen
API documentation is available at:
https://codedoc.pub/locomotivemtl/charcoal-cache/master/
Development Dependencies
Coding Style
The charcoal-cache module follows the Charcoal coding-style:
- PSR-1
- PSR-2
- PSR-4, autoloading is therefore provided by Composer.
- phpDocumentor comments.
- phpcs.xml.dist and .editorconfig for coding standards.
Coding style validation / enforcement can be performed with
composer phpcs
. An auto-fixer is also available withcomposer phpcbf
.