Symfony Bundle for the Stash Caching Library

Overview

TedivmStashBundle Build Status

License Latest Stable Version Coverage Status Total Downloads

The TedivmStashBundle integrates the Stash caching library into Symfony, providing a powerful abstraction for a range of caching engines. This bundle provides a caching service, adds Stash information to the Web Profiler toolbar, and adds integration for the Doctrine Common Cache library.

Both the bundle and Stash are licensed under the New BSD License. Please fork us on Github!

Installation

Add the bundle using composer, either by requiring it on the command line:

composer require tedivm/stash-bundle

or by adding it directly to your composer.json file:

"require": {
    "tedivm/stash-bundle": "0.7.*"
}

Add the bundle to app/AppKernel.php:

public function registerBundles()
{
    return array(
        new Tedivm\StashBundle\TedivmStashBundle(),
    );
}

And then set the basic configuration in app/config/config.yml:

stash: ~

Usage

Just fetch the default cache pool service:

$pool = $this->container->get('stash');

Or a custom-defined cache pool:

$pool = $this->container->get('stash.custom_cache');

Then you can use the cache service directly:

$item = $pool->getItem($id, 'info'); // cache keys, more than one can be used

$info = $item->get();

if($item->isMiss())
{
    $info = loadInfo($id);
    $item->set($userInfo, 60); // second parameter is TTL (in seconds or future \Datetime object)
}

return $info;

(See the Stash documentation for more information on using the cache service.)

Configuration

Default Cache Service

To get started quickly, you can define a single caching service with a single driver:

stash:
    drivers: [ FileSystem ]
    FileSystem: ~

This cache service will be registered as stash.default_cache, which will also be automatically aliased to cache.

Configuring Drivers

You can set the individual parameters of the cache driver directly in the configuration:

stash:
    drivers: [ FileSystem ]
    FileSystem:
        dirSplit: 3
        path: /tmp

Multiple Drivers

If you want to use multiple drivers in sequence, you can list them separately:

stash:
    drivers: [ Apc, FileSystem ]
    Apc: ~
    FileSystem:
        path: /tmp

The cache service will automatically be configured with a Composite driver, with the drivers queried in the specified order (for example, in this example, Apc would be queried first, followed by FileSystem if that query failed.)

In-Memory

By default, every cache service includes in-memory caching: during the lifetime of a single request, any values stored or retrieved from the cache service will be stored in memory, with the in-memory representation being checked before any other drivers. In some circumstances, however (such as long-running CLI batch scripts) this may not be desirable. In those cases, the in-memory driver can be disabled:

stash:
    drivers: [ Apc ]
    inMemory: false
    Apc: ~

Doctrine Adapter

Stash provides a Doctrine cache adapter so that your Stash caching service can be injected into any service that takes a DoctrineCacheInterface object. To turn on the adapter for a service, set the parameter:

stash:
    drivers: [ Apc ]
    registerDoctrineAdapter: true
    Apc: ~

For the default cache, the Adapter service will be added to the container under the name stash.adapter.doctrine.default_cache. You can use it anywhere you'd use a regular Doctrine Cache object:

doctrine:
    orm:
        metadata_cache_driver:
            type: service
            id: stash.adapter.doctrine.default_cache
        query_cache_driver:
            type: service
            id: stash.adapter.doctrine.default_cache
        result_cache_driver:
            type: service
            id: stash.adapter.doctrine.default_cache

Session Adapter

Stash provides a session adapter to allow Symfony sessions to be stored directly inside the cache. To turn on the adapter, set the parameter:

stash:
    drivers: [ Apc ]
    registerSessionHandler: true
    Apc: ~

Once it's enabled, enable it in the framework bundle and it will automatically be used:

framework:
    session:
        handler_id: stash.adapter.session.default_cache

Logger

Stash supports PSR Compliant logging libraries, you can specify which library is used by passing the logger's service name as a parameter:

stash:
	drivers: [ FileSystem ]
	logger: logger
	FileSystem: ~ 

Multiple Services

You can also configure multiple services, each of which stores is entirely separate:

stash:
    caches:
        first:
            drivers: [ FileSystem ]
            registerDoctrineAdapter: true
            FileSystem: ~
        second:
            drivers: [ Apc, FileSystem ]
            inMemory: false
            logger: logger
            FileSystem: ~

Each service is defined with keys inside a separate, distinct internal namespace, so you can use multiple services to avoid key collisions between distinct services even if you only have a single backend available.

When multiple caches are defined, you can manually define a default, which will be aliased to the stash service:

stash:
    default_cache: first
    first:
        ...
    second:
        ...

If you don't, the first service defined will be set as the default.

Tracking

StashBundle includes a module which tracks the keys of all cache queries made during a request for debugging purposes. By default this module is enabled in the dev and test environments but disabled elsewhere. However, if you want to override the default behavior, you can enable or disable this behavior in the configuration:

stash:
    tracking: true # enables query logging, false to disable
    tracking_values: true # enables query logging of full cache values, false to disable

Stash Driver Configuration

Each driver comes with a set of default options which can be individually overridden.

FileSystem:
    dirSplit:               2
    encoder:                Native
    path:                   %kernel.cache_dir%/stash
    filePermissions:        0660
    dirPermissions:         0770
    memKeyLimit:            20
SQLite:
    path:                   %kernel.cache_dir%/stash
    filePermissions:        0660
    dirPermissions:         0770
    busyTimeout:            500
    nesting:                0
    subdriver:              PDO
Apc:
    ttl:                    300
    namespace:              <none>
Memcache:
    servers:
        - { server: 127.0.0.1, port: 11211, weight: 1 }
Comments
  • Made bundle compatible with symfony 3.4

    Made bundle compatible with symfony 3.4

    I needed an upgrade for this bundle to prepare a symfony 4 upgrade of our platform.

    I made the code deprecation free. I also needed to update some dev dependencies (phpunit mainly) so I updated the unit tests also.

    This PR also drops support for PHP 5.4

    There is one issue that could be fixed by this PR https://github.com/tedious/TedivmStashBundle/issues/107

    opened by digibeuk 12
  • Logging causes memory use to increase forever

    Logging causes memory use to increase forever

    Todo:

    • [x] Add a logger which can be used in prod
    • [ ] Enable this logger by default in prod (unsure how this can be done, feel free to propose or take over if first commit looks ok)

    See prior discussion on #22.

    opened by andrerom 9
  • Unrecognized option

    Unrecognized option "Apc" under "stash.caches.default"

    With this in config.yml:

    stash:
        drivers: [ Apc ]
        registerDoctrineAdapter: true
        Apc:
            namespace: sf_stash_
    

    When doing app/console cache:clear with Symfony 2.8.1, getting this error: Unrecognized option "Apc" under "stash.caches.default"

    opened by layanto 8
  • setOptions on drivers is called twice

    setOptions on drivers is called twice

    We were having some trouble with the DriverFactory. In some drivers, specifically in our case, the FileSystem driver, the setOptions method has side-effects. The FileSystem driver creates the cache path, but even if it didn't we'd still have troubles, because it throws exceptions if there's something wrong with the cache path.

    Because of this it's important that the cache path passed to the Filesystem driver is correct. If it isn't we're attempting to create directories, or possibly getting exceptions thrown.

    Before this patch, setOptions were being called twice for all drivers. Once in the constructor of AbstractDriver, with the default (and in our case non-working) options, and once intentionally in the DriverFactory (with the correct options).

    This patch removes the unnecessary and possibly erroneous call by passing the options to the constructor instead of with a dedicated setOptions call.

    opened by magnusnordlander 7
  • symfony/symfony 2.7.0 compatibility fix

    symfony/symfony 2.7.0 compatibility fix

    In 2.7.0 those DIC methods were removed (BC break) thus container building crashes.

    This is NOT compatible with versions older than 2.6.0.

    DOC: http://symfony.com/doc/2.7/components/dependency_injection/factories.html

    opened by Im0rtality 7
  • cache service alias conflicts with Symfony's cache parameter in http cache mode

    cache service alias conflicts with Symfony's cache parameter in http cache mode

    "cache" is also used by symfony*, so the cache alias in this Bundle should be changed to something in stash namespace to avoid conflicts.

    * https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/HttpCache/HttpCache.php#L57

    see: https://github.com/tedivm/TedivmStashBundle/commit/363eece08fc6bb3f4e66c5065e50c2fe1b5172a0#L1R30

    opened by andrerom 7
  • Disable logging in the production environment

    Disable logging in the production environment

    This PR is in response to the discussion in #23 regarding memory leak issues with long-running scripts that utilize caching. It resolves the issue by turning off the logging of queries in the production environment, instead logging calls and hits only.

    opened by jhallbachner 6
  • Update to Stash 0.11 needed

    Update to Stash 0.11 needed

    As 0.10 is no longer supported, update to use 0.11 is needed to get the latests, Redis, windows, hhvm fixes and more: https://github.com/tedivm/Stash/compare/v0.10.5...v0.11.4

    opened by andrerom 5
  • Heroku deployment problems with memcache driver

    Heroku deployment problems with memcache driver

    So i'm trying to deploy to heroku using the memcache driver but I keep getting an exception when I attempt deployment.

    remote:          [Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]  
    remote:          Unrecognized option "Memcache" under "stash.caches.default" 
    

    The deploy works perfectly fine if if I change the driver back to FileSystem and the memcache configuration works just fine in my dev environment.

    Here is my config file:

    stash:
        caches:
        # The default cache should be used with care. Consider adding another cache
        # pool for something specific used in many places.
            default:
                drivers: [ Memcache ]
                Memcache:
                    servers:
                        - { server: %memcache_server%, port: 11211, weight: 1 }
            oauth:
                drivers: [ Memcache ]
                Memcache:
                    prefix_key: oauth_
                    servers:
                        - { server: %memcache_server%, port: 11211, weight: 1 }
                registerDoctrineAdapter: true
    
    opened by blackknight467 3
  • Made correction in README.md

    Made correction in README.md

    When making services dependent on "@cache" I was getting this error:

    The service "xxx.xxx" has a dependency on a non-existent service "cache".

    Switching to "@stash" fixed the issue - I also executed the "container:debug" command and it showed that "stash" was set up as an alias but had no entry for "cache".

    opened by AndrewCarterUK 3
  • Configurable logger

    Configurable logger

    As initially discussed in issue https://github.com/tedious/TedivmStashBundle/issues/60, this pull request adds a 'logger' config parameter to caches so that they may be injected when each cache is created.

    An example config:

    stash:
        caches:
            first:
                drivers: [ FileSystem ]
                registerDoctrineAdapter: true
                FileSystem: ~
                logger: logger
            second:
                drivers: [ Apc, FileSystem ]
                inMemory: false
                FileSystem ~
                logger: another_logger_service_name
    
    opened by samarties 3
  • Disable stashcache throughout project

    Disable stashcache throughout project

    Hello guys,

    We are using Stashcach bundle for Symfony2 project. It is very useful for caching.

    We have changed our production server mysql database. Currently problem we are facing is, even after changing database configuration, application updates data in older database. This seems issue due to caching of doctrine object by stashcache. So if there is any way that we can disable stashcache throughout the project, it wont cache doctrine object.

    Can anyone help in this regard.

    Thanks

    opened by mohit5540 0
  • Symfony Cache vs StashBundle

    Symfony Cache vs StashBundle

    With Symfony Cache about to be released with Symfony 3.1, what are the reasons to use StashBundle instead of the built in Symfony Cache component? Maybe grouping/hierarchical cache? Anything else?

    opened by layanto 0
  • Profiler Symfony and OutOfMemoryException

    Profiler Symfony and OutOfMemoryException

    Hi,

    In case of large data in cache, we got a OutOfMemoryException in the profiler :

    OutOfMemoryException in FileProfilerStorage.php line 159:
    Error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 33300466 bytes)
    

    A simple workaround is to disable variables tracking

    stash:
        tracking_values: false
    

    I don't have time to propose a PR but if someone want to work on this, he can begin to have a look in Tedivm\StashBundle\Collector\CacheDataCollector and deduplicate data.

    Mehdi

    opened by mehdi-ghezal 0
  • Issue with Symfony 2.8.3 and the new symfony/polyfill-apcu

    Issue with Symfony 2.8.3 and the new symfony/polyfill-apcu

    I believe the problem is more on the polyfill side, but just to keep you in the loop : Since Symfony 2.8.3 the symfony/polyfill-apcu is required, and if the system doesnt have APCIterator or APCUIterator, Stash trigger a fatal error when calling class_exists('\APCUIterator'); since the class is known by Composer's autoloader but can't be instanciate as it extend \APCIterator that doesnt exist on all system.

    https://github.com/symfony/polyfill/issues/39

    opened by fgrandjean 2
  • Redis config socket

    Redis config socket

    https://github.com/tedious/TedivmStashBundle/commit/6c24926a0a2c526b9478e531832af843e64a4787

    Is setting redis servers.socket to a boolean node a bug? Shouldn't it be a string?

    opened by scragg0x 0
Releases(v0.7.1)
  • v0.7.1(Aug 9, 2022)

    What's Changed

    • docs: update composer command to 0.7 by @andheiberg in https://github.com/tedious/TedivmStashBundle/pull/109
    • fix php8 compatibility by @jmleroy in https://github.com/tedious/TedivmStashBundle/pull/111

    New Contributors

    • @jmleroy made their first contribution in https://github.com/tedious/TedivmStashBundle/pull/111

    Full Changelog: https://github.com/tedious/TedivmStashBundle/compare/v0.7.0...v0.7.1

    Source code(tar.gz)
    Source code(zip)
  • v0.6.2(Feb 28, 2017)

    Code changes:

    • Added support for the 'remove_failed_servers' option of the memcached extension (#101)
    • Fix missing set item TTL after PSR-6 change (#102)

    Doc Changes:

    • More meaningful error message (#98)
    • Fix case-sensitive driver key (#99)
    • Update composer require version in README (#100)
    Source code(tar.gz)
    Source code(zip)
  • v0.6.1(Feb 11, 2016)

  • v0.5.3(Dec 29, 2015)

    • Made sure AbstractDriver::setOptions is called only once in the DriverFactory.
    • Symfony3 support.
    • PHP 7.0 support (tests on PHP 7.0 are not allowed to fail anymore).
    Source code(tar.gz)
    Source code(zip)
  • v0.5.1(Aug 2, 2015)

    • Dropped support for PHP 5.3.
    • Added 'logger' config parameter to caches so that they may be injected when each cache is created.
    • Compatibility updates for our upstream projects.
    Source code(tar.gz)
    Source code(zip)
  • v0.4.2(Dec 8, 2014)

  • v0.4.1(Jun 5, 2014)

    Major Updates:

    • Upgrade to Stash v0.12
    • Full HHVM Support.
    • Removed PEAR Support.
    • Added metadocuments like LICENSE, CONTRIBUTORS, and docs/index.srt.
    • Updated Readme with more project status news and to reflect the changes in this version.
    • Massive Documentation Update, with complete DocBlock and file level documentation.
    • Full Doctrine Cache Support via DoctrineAdapter.
    • Improved Redis support.

    Test Suite Updates:

    • 98% code coverage- more than half of the changes from this update come from improved test suites.
    • Test against parent/upstream test suites.
    • Enforcement of Formatting and Coding Standards.
    • Refactored internal API for easier testing.
    • Improved Travis-CI Integration.
    • Coveralls Support.
    Source code(tar.gz)
    Source code(zip)
  • v0.2.4(Jan 23, 2014)

    This addition to the 0.2 line is meant to some more memcache options into that line of code. You should migrate up to the 0.3 line if you can, but if you're stuck on 0.2 and need those memcache options this is for you!

    Source code(tar.gz)
    Source code(zip)
  • v0.3.2(Jan 22, 2014)

  • v0.3.1(Jan 8, 2014)

    This update is mainly to bring this bundle up to date with Stash, which is now on the 0.11 line. As there have been some backwards incompatibility changes in Stash from 0.10 to 0.11 it's recommended that you look at the Stash Changelog before upgrading.

    Notable updates include logging support, better windows support, and a refactoring of interface locations.

    Source code(tar.gz)
    Source code(zip)
Owner
Tedious Developments
Libraries That Prevent Boredom
Tedious Developments
Stash makes it easy to speed up your code by caching the results of expensive functions or code

Stash - A PHP Caching Library Stash makes it easy to speed up your code by caching the results of expensive functions or code. Certain actions, like d

Tedious Developments 943 Dec 15, 2022
[READ-ONLY] Easy to use Caching library with support for multiple caching backends. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Caching Library The Cache library provides a Cache service locator for interfacing with multiple caching backends using a simple to use interf

CakePHP 49 Sep 28, 2022
Caching implementation with a variety of storage options, as well as codified caching strategies for callbacks, classes, and output

laminas-cache Laminas\Cache provides a general cache system for PHP. The Laminas\Cache component is able to cache different patterns (class, object, o

Laminas Project 69 Jan 7, 2023
This plugin integrates cache functionality into Guzzle Bundle, a bundle for building RESTful web service clients.

Guzzle Bundle Cache Plugin This plugin integrates cache functionality into Guzzle Bundle, a bundle for building RESTful web service clients. Requireme

Vlad Gregurco 11 Sep 17, 2022
Yii Caching Library - Redis Handler

Yii Caching Library - Redis Handler This package provides the Redis handler and implements PSR-16 cache. Requirements PHP 7.4 or higher. Installation

Yii Software 4 Oct 9, 2022
This is a Symfony bundle that lets you you integrate your PSR-6 compliant cache service with the framework

PSR-6 Cache bundle This is a Symfony bundle that lets you you integrate your PSR-6 compliant cache service with the framework. It lets you cache your

null 43 Oct 7, 2021
A thin PSR-6 cache wrapper with a generic interface to various caching backends emphasising cache tagging and indexing.

Apix Cache, cache-tagging for PHP Apix Cache is a generic and thin cache wrapper with a PSR-6 interface to various caching backends and emphasising ca

Apix 111 Nov 26, 2022
Query caching for Laravel

Query caching for Laravel

Dwight Watson 1k Dec 30, 2022
Simple Yet Powerful PHP Caching Class

The PHP high-performance object caching system ever. phpFastCache is a high-performance, distributed object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load. phpFastCache dropped the database load to almost nothing, yielding faster page load times for users, better resource utilization. It is simple yet powerful

Khoa Bui 28 Aug 19, 2022
Caching extension for the Intervention Image Class

Intervention Image Cache extends the Intervention Image Class package to be capable of image caching functionality.

null 616 Dec 30, 2022
DataLoaderPhp is a generic utility to be used as part of your application's data fetching layer to provide a simplified and consistent API over various remote data sources such as databases or web services via batching and caching.

DataLoaderPHP is a generic utility to be used as part of your application's data fetching layer to provide a simplified and consistent API over various remote data sources such as databases or web services via batching and caching.

Webedia - Overblog 185 Nov 3, 2022
The next-generation caching layer for PHP

The next-generation caching layer for PHP

CacheWerk 115 Dec 25, 2022
Symfony2 Bundle for Doctrine Cache

DoctrineCacheBundle Symfony Bundle for Doctrine Cache. Master: Master: Deprecation warning This bundle is abandoned and will no longer be updated. If

Doctrine 2.8k Dec 9, 2022
CLI App and library to manage apc & opcache.

CacheTool - Manage cache in the CLI CacheTool allows you to work with APCu, OPcache, and the file status cache through the CLI. It will connect to a F

Samuel Gordalina 1.4k Jan 3, 2023
PHP cache library, with adapters for e.g. Memcached, Redis, Couchbase, APC(u), SQL and additional capabilities (e.g. transactions, stampede protection) built on top.

Donate/Support: Documentation: https://www.scrapbook.cash - API reference: https://docs.scrapbook.cash Table of contents Installation & usage Adapters

Matthias Mullie 295 Nov 28, 2022
A simple cache library. Implements different adapters that you can use and change easily by a manager or similar.

Desarolla2 Cache A simple cache library, implementing the PSR-16 standard using immutable objects. Caching is typically used throughout an applicatito

Daniel González 129 Nov 20, 2022
A library providing platform-specific user directory paths, such as config and cache

Phirs A library providing platform-specific user directory paths, such as config and cache. Inspired by dirs-rs.

Mohammad Amin Chitgarha 7 Mar 1, 2022
A simple cache library. Implements different adapters that you can use and change easily by a manager or similar.

Desarolla2 Cache A simple cache library, implementing the PSR-16 standard using immutable objects. Caching is typically used throughout an applicatito

Daniel González 129 Nov 20, 2022
Stash - A PHP Caching Library

Stash - A PHP Caching Library Stash makes it easy to speed up your code by caching the results of expensive functions or code. Certain actions, like d

Tedious Developments 943 Dec 15, 2022
Stash view is a composer package for Laravel which caches views using Russian Doll Caching methodology.

Stash View Stash view is a composer package for Laravel which caches views using Russian Doll Caching methodology. What is Russian Doll Caching ? It i

Bhushan Gaikwad 18 Nov 20, 2022