Giter VIP home page Giter VIP logo

cache's Introduction

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.

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

PSR-16 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

Additional methods

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

cache's People

Contributors

ajbdev avatar asmecher avatar benswinburne avatar bryantaxs avatar desarrolla2 avatar echernyavskiy avatar gresakg avatar gries avatar itn3rd77 avatar jasny avatar juliangut avatar lukasz-schab avatar nike-17 avatar ozziest avatar poratuk avatar pranavpc avatar ragboyjr avatar scottrobertson avatar sunspikes avatar woutersamaey avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cache's Issues

Mongo adapter v2

The Mongo adapter is no longer present in v2.

Note that the Mongo class has been deprecated instead the MongoClient/MongoDB class should be used.

How to clear cache?

Hi,

What is the proper way to flush the cache and remove all keys completely?

Thanks,
San

Cache chain

Chain multiple other adapters together. Setting an entry will set it for all backends. Getting will try the first and on a miss try the second, etc. This is useful to have local cache and cache server. And/or fast short-lived cache and slower long-lived cached. In that case, set the (max) ttl per adapter.

use Desarrolla2\Cache\Chain as CacheChain;
use Desarrolla2\Cache\PhpFile as PhpFileCache;
use Desarrolla2\Cache\Memcached as MemcachedCache;
use Desarrolla2\Cache\S3 as S3Cache;

$cache = new CacheChain([
  (new PhpFileCache('/tmp'))->withOption('ttl', 3600),
  (new MemcachedCache('/tmp'))->withOption('ttl', 24 * 3600),
  (new S3Cache('s3:example_bucket/mycache'))->withOption('ttl', 30 * 24 * 3600)
]);

PDO implementation

http://php.net/manual/en/book.pdo.php

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions. Note that you cannot perform any database functions using the PDO extension by itself; you must use a database-specific PDO driver to access a database server.

Unlike other database implementations, all queries need to be configured.

PHP Redis

Have you thought about supporting phpredis extension?

Memcache ttl issue

Hi,

I initiate memcache as

$adapter = new \Desarrolla2\Cache\Adapter\MemCache();
$adapter->addServer('localhost', 11211);
$cache = new \Desarrolla2\Cache\Cache($adapter);

and try to set some data as

if (!$cache->has("last")) {
$d = $pimple['HomeController']->getLastPlaces(15);
$cache->set("last", $d, 10);
}

$data["res"] = $cache->get("last");

i assume i give 10 secs to store data but before 10 secs past, I change getLastPlaces(15) to getLastPlaces(20); it fetch still getLastPlaces(15) data if even 10 secs passes. What i miss? (Sorry bout my english)

msgpack packer

https://msgpack.org/
https://pecl.php.net/package/msgpack

MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it's faster and smaller. Small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves.

RethinkDB implementation

https://rethinkdb.com/

RethinkDB pushes JSON to your apps in realtime.
When your app polls for data, it becomes slow, unscalable, and cumbersome to maintain.

RethinkDB is the open-source, scalable database that makes building realtime apps dramatically easier.

PostgreSQL implementation

http://php.net/manual/en/intro.pgsql.php

PostgreSQL database is an Open Source product and available without cost. Postgres, developed originally in the UC Berkeley Computer Science Department, pioneered many of the object-relational concepts now becoming available in some commercial databases. It provides SQL92/SQL99 language support, transactions, referential integrity, stored procedures and type extensibility. PostgreSQL is an open source descendant of this original Berkeley code.

Model after Mysqli implementation.

getTtl() recursion problem

Uncaught Exception Error: "Maximum function nesting level of '256' reached, aborting!"

File adapter
ttlStrategy=mtime

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.

SQLite implementation

http://php.net/manual/en/book.sqlite3.php

SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. The code for SQLite is in the public domain and is thus free for use for any purpose, commercial or private. SQLite is the most widely deployed database in the world with more applications than we can count, including several high-profile projects.

SQLite is an embedded SQL database engine. Unlike most other SQL databases, SQLite does not have a separate server process. SQLite reads and writes directly to ordinary disk files. A complete SQL database with multiple tables, indices, triggers, and views, is contained in a single disk file. The database file format is cross-platform - you can freely copy a database between 32-bit and 64-bit systems or between big-endian and little-endian architectures. These features make SQLite a popular choice as an Application File Format. SQLite database files are a recommended storage format by the US Library of Congress. Think of SQLite not as a replacement for Oracle but as a replacement for fopen().

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);

using opcache.preload error

using opcache.preload I get the error below.

Fatal err[24-Jan-2021 12:19:52] PHP Fatal error: Declaration of Desarrolla2\Cache\MongoDB::initialize() must be compatible with Desarrolla2\Cache\Option\InitializeTrait::initialize(): void in /var/www/vendor/desarrolla2/cache/src/MongoDB.php on line 52

Couchbase implementation

https://www.couchbase.com/

Couchbase Server is an open source, distributed, NoSQL document-oriented engagement database. It exposes a fast key-value store with managed cache for sub-millisecond data operations, purpose-built indexers for fast queries and a powerful query engine for executing SQL-like queries. For mobile and Internet of Things environments Couchbase also runs natively on-device and manages synchronization to the server.

Azure Blob storage

https://azure.microsoft.com/nl-nl/services/storage/blobs/

Massively scalable object storage for unstructured data
With exabytes of capacity and massive scalability, Blob Storage stores from hundreds to billions of objects in hot, cool or archive tiers, depending on how often data access is needed. Store any type of unstructured data – images, videos, audio, documents and more – easily and cost-effectively.

Similar to AWS S3

Yac implementation

https://pecl.php.net/package/yac

yac is a shared memory user data cache for PHP. it can be used to replace APC or local memcached.

yac is lockless, that means, it is very fast, but there could be a chance you will get a wrong data(depends on how many key slots are allocated and how many keys are stored), so you'd better make sure that your product is not very sensitive to that.

Implement tests for implementation specific options

Currently, we're only running generic PSR-16 tests. We'd also like to test the different options of each implementation.

Additionally, we want to test features that may be missed by the general tests. We're aiming at 100% coverage.

Bug in Version 1.8.0

In the File.php - Line 100 you use short array notation and the composer required 5.3.3. Short notation appear in 5.4 no?

Otherwise work awesome

AWS S3 implementation

https://docs.aws.amazon.com/aws-sdk-php/v3/api/namespace-Aws.S3.html

AWS object store. Useful to store cache for a longer period of time.

https://docs.aws.amazon.com/AmazonS3/latest/dev/lifecycle-expire-general-considerations.html

When an object reaches the end of its lifetime, Amazon S3 queues it for removal and removes it asynchronously. There may be a delay between the expiration date and the date at which Amazon S3 removes an object. You are not charged for storage time associated with an object that has expired.

Doctrine adapter

https://www.doctrine-project.org/

The Doctrine Project is the home to several PHP libraries primarily focused on database storage and object mapping. The core projects are the Object Relational Mapper (ORM) and the Database Abstraction Layer (DBAL) it is built upon.

dbx implementation

http://php.net/manual/en/book.dbx.php

The dbx module is a database abstraction layer (db 'X', where 'X' is a supported database). The dbx functions allow you to access all supported databases using a single calling convention. The dbx-functions themselves do not interface directly to the databases, but interface to the modules that are used to support these databases.

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?

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.

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();

igBinary packer

https://pecl.php.net/package/igbinary

Igbinary is a drop in replacement for the standard php serializer. Instead of time and space consuming textual representation, igbinary stores php data structures in compact binary form. Savings are significant when using memcached or similar memory based storages for serialized data. About 50% reduction in storage requirement can be expected. Specific number depends on your data.

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.

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.

has() in File adapter false negative

The has() method in the File adapter fails if the value is there but false/null/0 etc.

public function has($key)
{
    if (!$this->getData($key)) {
        return false;
    }
    return true;
}

getData($key) can exist and then return false (or equivalent) but this causes a false negative when determining if there's a value in the cache.

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: facebook/hhvm#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.

Redis Support

Hi i have to say nice project was wondering if you could add a Redis adapter.

When will the phpredis adapter be released to composer?

I'm looking for a simple psr-16 caching library instead of doctrine/cache. I think this project is a better choice compared to similar projects like symfony/cache or cache/cache

But php redis is a component I have to use, I found it was committed to dev-master months ago, when will it be released?

Based on the stability, will this project continue to be maintained in the future?

Packer chain

Use multiple packers by chaining them. This is especially useful for encryption.

Search keys by pattern

$adapter = new Apc();
$cache = new Cache($adapter);
$cache->set('user1' 'myValue');
$cache->set('user2' 'myValue');
$cache->getKeys('user*'); // wil return [ 'user1', 'user2']

Database for cache.

What is the mysql database structure you have used for cache in mysql database.

The file is read twice to get the cache value.

Version 3.0.1
File adapter
ttlStrategy=embed

The file is read twice to get the cache value.
For the first time in has()
And the second - readFile()

This was in one read operation in 2.x version.

Prefix option should affect clear()

Clearing the cache works by deleting a whole directory, table, collection, etc. Options like prefix don't affect what is and isn't cleared. This may give unexpected side effects.

While this can easily be changed for some implementations, we choose to keep this consistent.

Clearing all cache is almost always faster than doing this item per item. So the behaviour (fast vs correct) should be optional.

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.