A simple cache library. Implements different adapters that you can use and change easily by a manager or similar.

Related tags

Caching Cache
Overview

Desarolla2 Cache

A simple cache library, implementing the PSR-16 standard using immutable objects.

life-is-hard-cache-is

Caching is typically used throughout an applicatiton. Immutability ensure that modifying the cache behaviour in one location doesn't result in unexpected behaviour due to changes in unrelated code.

Desarolla2 Cache aims to be the most complete, correct and best performing PSR-16 implementation available.

Latest version Latest version Software License Build Status Coverage Status Quality Score Total Downloads Today Downloads Gitter

Installation

composer require desarrolla2/cache

Usage

use Desarrolla2\Cache\Memory as Cache;

$cache = new Cache();

$value = $cache->get('key');

if (!isset($value)) {
    $value = do_something(); 
    $cache->set('key', $value, 3600);
}

echo $value;

Adapters

The following implementation allows you to combine cache adapters.

Other implementations are planned. Please vote or provide a PR to speed up the process of adding the to this library.

Options

You can set options for cache using the withOption or withOptions method. Note that all cache objects are immutable, setting an option creates a new object.

TTL

All cache implementations support the ttl option. This sets the default time (in seconds) that cache will survive. It defaults to one hour (3600 seconds).

Setting the TTL to 0 or a negative number, means the cache should live forever.

Methods

Each cache implementation has the following Psr\SimpleCache\CacheInterface methods:

get(string $key [, mixed $default])

Retrieve the value corresponding to a provided key

has(string $key)

Retrieve the if value corresponding to a provided key exist

set(string $key, mixed $value [, int $ttl])

Add a value to the cache under a unique key

delete(string $key)

Delete a value from the cache

clear()

Clear all cache

getMultiple(array $keys)

Obtains multiple cache items by their unique keys

setMultiple(array $values [, int $ttl])

Persists a set of key => value pairs in the cache

deleteMultiple(array $keys)

Deletes multiple cache items in a single operation

.

The Desarrolla2\Cache\CacheInterface also has the following methods:

withOption(string $key, string $value)

Set option for implementation. Creates a new instance.

withOptions(array $options)

Set multiple options for implementation. Creates a new instance.

getOption(string $key)

Get option for implementation.

Packers

Cache objects typically hold a Desarrolla2\Cache\Packer\PackerInterface object. By default, packing is done using serialize and unserialize.

Available packers are:

  • SerializePacker using serialize and unserialize
  • JsonPacker using json_encode and json_decode
  • NopPacker does no packing
  • MongoDBBinaryPacker using serialize and unserialize to store as BSON Binary

PSR-16 incompatible packers

The JsonPacker does not fully comply with PSR-16, as packing and unpacking an object will probably not result in an object of the same class.

The NopPacker is intended when caching string data only (like HTML output) or if the caching backend supports structured data. Using it when storing objects will might give unexpected results.

Contributors

Daniel González Twitter: @desarrolla2
Arnold Daniels Twitter: @ArnoldDaniels

Comments
  • Remove duplicate invocation of getKey() in File::getValueFromCache()

    Remove duplicate invocation of getKey() in File::getValueFromCache()

    Calling getKey() before passing the key to getFileName() from getValueFromCache() is not only unnecessary, it actually breaks caching if the prefix is not empty. I discovered this from a slightly different perspective: in my application I had to inherit from Adapter/File and override getKey() so that it applies sha1() to it as I frequently get cache keys with colons and other garbage in them. So as with a non-empty prefix, the key gets mutated in this instance, and then gets mutated yet again by the second getKey() call, so the lookup key is actually completely different.

    opened by echernyavskiy 6
  • Not abandoning the project

    Not abandoning the project

    @desarrolla2 Unfortunately, v3 (the PSR-16 implementation I worked on) hasn't caught on. In the meantime, other implementations like http://www.php-cache.com are widely used.

    It doesn't seem worth it to continue working on this project. New projects better switch to another PSR-16 compatible library. Old projects can continue using v2, even if the project is abandoned.

    I'm also closing all the issues with features I planned to add.

    opened by jasny 4
  • Mongo and memcache

    Mongo and memcache

    I try to store fetched data from mongo in memcache. But it throws error.

    So i changed get and set functions in Desarrolla2\Cache\Adapter\MemCache\MemCache.php file to

    /** * {@inheritdoc } */ public function get($key) { $tKey = $this->getKey($key); $data = $this->server->get($tKey); if (!is_array($data)) return $this->unserialize($data); else return $data;

    }
    
    /**
     * {@inheritdoc }
     */
    public function set($key, $value, $ttl = null)
    {
    
        $tKey = $this->getKey($key);
    
        if (!is_array($value))
            $tValue = $this->serialize($value);
        else
            $tValue = $value;
    
        if (!$ttl) {
            $ttl = $this->ttl;
        }
        $this->server->set($tKey, $tValue, time() + $ttl);
    }
    

    maybe you can change ur file as mines. Btw thank you for your great lib.

    opened by rhnkyr 4
  • Move away from adapter / wrapper

    Move away from adapter / wrapper

    The Cache class is a wrapper around an adapter. It doesn't seem to have any benefit.

    Instead we can rename the adapters and change them to implement PSR-16. That way they can be used directly.

    use Dessarolla2\Cache;
    
    $cache = new Cache\Apu();
    
    opened by jasny 3
  • Added Mongo support.

    Added Mongo support.

    Added Mongo support.

    This was supported in 1.8, but missing in 2.0 Supports both the mongodb\mongodb library as the (legacy) mongo extension

    Differenes from 1.8:

    • Constructor takes db object or collection object as argument
    • Use _id field rather than custom key field
    • Expired items are ignored rather than deleted (just like Mysqli)
    • Using upsert rather than delete + insert
    • Store TTL as date bson type to allow ttl index

    Includes unit tests. Usage guide is added to README.

    Fixes desarrolla2/Cache#25

    opened by jasny 3
  • Add PHP file caching

    Add PHP file caching

    We can leverage opcode caching to create a very fast caching method in PHP 7+.

    To set the cache use var_export to get the value as PHP code and than write that to a PHP file. To get the cache simply use include.

    Read more about it in this article.

    opened by jasny 2
  • Problem in unserializing DateTime in HHVM

    Problem in unserializing DateTime in HHVM

    I have detected a problem in serializing and unserializing DateTime in HHVM:

    Error: exception 'Exception' with message 'DateTimeZone::__construct(): Unknown or bad timezone ()' in /Applications/MAMP/htdocs/Rai-DigitalOcean/vendor/desarrolla2/cache/src/Adapter/AbstractAdapter.php:92 
    Stack trace: #0 (): DateTime->__wakeup() 
    #1 /Applications/MAMP/htdocs/Rai-DigitalOcean/vendor/desarrolla2/cache/src/Adapter/AbstractAdapter.php(92): unserialize() 
    #2 /Applications/MAMP/htdocs/Rai-DigitalOcean/vendor/desarrolla2/cache/src/Adapter/File.php(153): Desarrolla2\Cache\Adapter\AbstractAdapter->unPack() 
    #3 /Applications/MAMP/htdocs/Rai-DigitalOcean/vendor/desarrolla2/cache/src/Adapter/File.php(63): Desarrolla2\Cache\Adapter\File->getValueFromCache() 
    #4 /Applications/MAMP/htdocs/Rai-DigitalOcean/vendor/desarrolla2/cache/src/Cache.php(57): Desarrolla2\Cache\Adapter\File->get() 
    #5 /Applications/MAMP/htdocs/Rai-DigitalOcean/app/Service/Product/ProductService.php(142): Desarrolla2\Cache\Cache->get() 
    #6 /Applications/MAMP/htdocs/Rai-DigitalOcean/resources/views/admin/products.php(8): Service\Product\ProductService->getAllProducts() 
    #7 /Applications/MAMP/htdocs/Rai-DigitalOcean/vendor/damnstupidsimple/core/src/Viewer.php(107): include() 
    #8 /Applications/MAMP/htdocs/Rai-DigitalOcean/vendor/damnstupidsimple/core/src/Viewer.php(75): Core\Viewer::render() 
    #9 /Applications/MAMP/htdocs/Rai-DigitalOcean/app/Controller/Admin.php(41): Core\Viewer::file() 
    #10 (): Controller\Admin->displayAnyPage() 
    #11 /Applications/MAMP/htdocs/Rai-DigitalOcean/vendor/damnstupidsimple/core/src/Router.php(818): call_user_func_array() 
    #12 /Applications/MAMP/htdocs/Rai-DigitalOcean/app/bootstrap.php(130): Core\Router::dispatch() 
    #13 /Applications/MAMP/htdocs/Rai-DigitalOcean/index.php(56): include() 
    #14 {main}
    

    Issue: https://github.com/facebook/hhvm/issues/6783

    Reproducing Error:

    $cache =  new Cache($adapter);
    $time =  \DateTime::createFromFormat('U', time());
    $cache->set('time', $time, 3600);
    $cache->get('time'); // error here when unserializing the DateTime object
    

    My workaround now is to use NotCache at the current time.

    HHVM 
    opened by farizluqman 2
  • File implementation TTL and cleanup

    File implementation TTL and cleanup

    The File adapter has no cleanup for TTL. As such, everything lives on the file system forever. Somewhat surprised to see my cache dir grow to 1.3G. I'd like to contribute something here but not sure if anyone has any input. Perhaps a cleanup probability during set()? Somewhat similar to php's own garbage collection probability?

    Or perhaps support implementing their own Cleanup interface for now?

    v3 
    opened by aaronpeterson 2
  • Fixed wrong SQL in src/Mysqli.php

    Fixed wrong SQL in src/Mysqli.php

    Fixed wrong NOW() (returns 'YYYY-MM-DD hh:mm:ss') to UNIX_TIMESTAMP() (returns INT/BIGINT). NOW() causes the cache to be cleared on every event execution.

    opened by raubv0gel 1
  • Implement PSR-16

    Implement PSR-16

    PSR-16 is a standard cache interface.

    Caching is a common way to improve the performance of any project, making caching libraries one of the most common features of many frameworks and libraries. Interoperability at this level means libraries can drop their own caching implementations and easily rely on the one given to them by the framework, or another dedicated cache library.

    PSR-6 is a different caching standard, which may also be implemented, but seems rather complicated and very much differs from the current implementation.

    PSR-6 solves this problem already, but in a rather formal and verbose way for what the most simple use cases need. This simpler approach aims to build a standardized streamlined interface for common cases. It is independent of PSR-6 but has been designed to make compatibility with PSR-6 as straightforward as possible.

    opened by jasny 1
  • Setup server host

    Setup server host

    For example, when memcache server is not on the same server than php script. We have to do this

    $memcache = new \Memcache();
    $memcache->addServer('XX.XX.XX.XX', 11211);
    $adapter = new \Desarrolla2\Cache\Adapter\Memcache($memcache);
    

    and maybe delete this line in the constructor :

    $this->server->addServer('localhost', 11211);
    
    opened by nums 1
  • Uncaught Error: Cannot use object of type stdClass as array in vendor/desarrolla2/cache/src/MongoDB.php on line 102

    Uncaught Error: Cannot use object of type stdClass as array in vendor/desarrolla2/cache/src/MongoDB.php on line 102

    I have stored a MongoDB\BSON\Persistable into the MongoDB cache with default settings. However, when trying to retrieve it, it throws the error "Cannot use object of type stdClass as array"

    opened by miklcct 1
  • Unable to clear the cache

    Unable to clear the cache

    I am getting following error.

    PHP Fatal error: Uncaught Desarrolla2\Cache\Exception\CacheException: not ready yet in vendor/desarrolla2/cache/src/Adapter/AbstractAdapter.php:61

    It looks like it is not implemented yet.

    opened by msaus 2
Releases(v3.0.0)
  • v3.0.0(Nov 21, 2018)

  • v3.0.0-beta1(Jun 23, 2018)

Owner
Daniel González
Team Manager and Developer | PHP | Symfony. I am founder of @phpmad and @symfony-madrid communities.
Daniel González
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 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
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 high-performance backend cache system. It is intended for use in speeding up dynamic web applications by alleviating database load.

A high-performance backend cache system. It is intended for use in speeding up dynamic web applications by alleviating database load. Well implemented, it can drops the database load to almost nothing, yielding faster page load times for users, better resource utilization. It is simple yet powerful.

PHPSocialNetwork 2.3k Dec 30, 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
[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
:zap: Simple Cache Abstraction Layer for PHP

⚡ Simple Cache Class This is a simple Cache Abstraction Layer for PHP >= 7.0 that provides a simple interaction with your cache-server. You can define

Lars Moelleken 27 Dec 8, 2022
Simple cache abstraction layer implementing PSR-16

sabre/cache This repository is a simple abstraction layer for key-value caches. It implements PSR-16. If you need a super-simple way to support PSR-16

sabre.io 48 Sep 9, 2022
Simple cache

Simple cache

Róbert Kelčák 3 Dec 17, 2022
Simple artisan command to debug your redis cache. Requires PHP 8.1 & Laravel 9

?? php artisan cache:debug Simple artisan command to debug your redis cache ?? Installation You can install the package via composer: composer require

Juan Pablo Barreto 19 Sep 18, 2022
The cache component provides a Promise-based CacheInterface and an in-memory ArrayCache implementation of that

Cache Async, Promise-based cache interface for ReactPHP. The cache component provides a Promise-based CacheInterface and an in-memory ArrayCache imple

ReactPHP 330 Dec 6, 2022
LaraCache is an ORM based package for Laravel to create, update and manage cache items based on model queries

LaraCache Using this package, you can cache your heavy and most used queries. All you have to do is to define the CacheEntity objects in the model and

Mostafa Zeinivand 202 Dec 19, 2022
The place to keep your cache.

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 944 Jan 4, 2023
Cache slam defense using a semaphore to prevent dogpile effect.

metaphore PHP cache slam defense using a semaphore to prevent dogpile effect (aka clobbering updates, stampending herd or Slashdot effect). Problem: t

Przemek Sobstel 102 Sep 28, 2022
Doctrine Cache component

Doctrine Cache Cache component extracted from the Doctrine Common project. Documentation This library is deprecated and will no longer receive bug fix

Doctrine 7.6k Jan 3, 2023
LRU Cache implementation in PHP

PHP LRU Cache implementation Intro WTF is a LRU Cache? LRU stands for Least Recently Used. It's a type of cache that usually has a fixed capacity and

Rogério Vicente 61 Jun 23, 2022
PSR-6 cache implementation adapting a given PSR-16 instance

PSR-6 cache implementation adapting PSR-16 This package provides a PSR-6 cache instance when you only have a PSR-16 cache at hand. As PSR-6 is more fe

null 1 Oct 15, 2021
More Than Just a Cache: Redis Data Structures

More Than Just a Cache: Redis Data Structures Redis is a popular key-value store, commonly used as a cache or message broker service. However, it can

Andy Snell 2 Oct 16, 2021