Code Monkey home page Code Monkey logo

hybridcache's Introduction

Hybrid Cache for PHP >= 5.3.x

Example of usage:

<?php

// require init.php for autoload classes
require('vendor/autoload.php');

use Hybrid\Cache;

// Use other name for no conflicts with Memcache Class
use Hybrid\Storages\Memcache as MemcacheStorage;

// add a MediaStorage to the Cache class:
Cache::addStorageMedia( new MemcacheStorage('localhost') );

// create a cache instance, with an identifier (can be a lot of values):
$cache = Cache::create(__FILE__, 'list top users');

// check if cache exists and is aviable


$data = $cache->getCacheOr(true, function ($cache) {
    // make your heavy processing.... (saving the result in a variable)
    return $result;
});

// Or...

if ($data = $cache->getCache(true)) {
   // dump cached data
   echo $data;
   // stop the script (or the method, ect)
   exit(0);
} else {
   // set the cache status as "saving" (to avoid duplicating entries)
   $cache->setStatusSaving();
}

// make your heavy processing.... (saving the result in a variable)

// dump the result
echo $result;

// cache the result
$cache->save($result);

Multiples storages

Currently, Hybrid Cache includes drivers for caching on Disk, Memcache and Redis, but you can extend it creating your own key/value storage connector, implementing the Hybrid\StorageMedia interface.

Storage instances can be assigned for reading and writing, and you can have multiple different storage systems.

Replication

Consider you have the following scenario using Redis:

 10.1.30.1   Redis master
       10.1.30.2  Redis replican
       10.1.30.3  Redis replican
       10.1.30.4  Redis replican
       10.1.30.5  Redis replican

You can set it up like this:

<?php

use Hybrid\Storages\Redis as RedisStorage;

// Define Redis server for write only (master)
Cache::addStorageMedia( new RedisStorage('10.1.30.1'), Cache::FOR_WRITE );

// Define the rest of servers for read only
Cache::addStorageMedia( new RedisStorage('10.1.30.2'), Cache::FOR_READ );
Cache::addStorageMedia( new RedisStorage('10.1.30.3'), Cache::FOR_READ );
Cache::addStorageMedia( new RedisStorage('10.1.30.4'), Cache::FOR_READ );
Cache::addStorageMedia( new RedisStorage('10.1.30.5'), Cache::FOR_READ );

By default, HybridCache uses a hash-based mechanism to balance load on multiple storage media. In this case, each server will receive the same amount of petitions. In a replication scenario a random petition distribution is more effective and HybridCache can try using another server on the list if the first one doesn't return anything.

To change the balancing method you should change the balanceMethod property of the instance:

<?php

$cache = Cache::create('key');
$cache->balanceMethod = Cache::B_RANDOM;

However, if you wish to apply the change globally for all new instances of the HybridCache class, you can define a constant:

<?php

define('CACHE_BALANCE_METHOD',Cache::B_RANDOM);

Note that the random method is extremely inefficient when there are several master servers.

Horizontal scalability

Horizontal scalability can be achieved with any storage media and sometimes it's better than replication.

In this case you define a number of storage media and the balancing is done using a hash generated by the key-value pair. All backend use the same algorithm, so they will all fetch the cache on the corresponding storage medium. It is very important to define the storages in the same order in all the backend servers, since the algorithm is based on the order and amount of them.

By default HybridCache uses a hash balance method, but if you want to be sure, you can set it explicitly:

<?php

define('CACHE_BALANCE_METHOD',Cache::B_HASH);

To define a scalation array:

<?php

use Hybrid\Storages\Memcache as MemcacheStorage;

Cache::addStorageMedia( new MemcacheStorage('10.1.30.1') );
Cache::addStorageMedia( new MemcacheStorage('10.1.30.2') );
Cache::addStorageMedia( new MemcacheStorage('10.1.30.3') );
Cache::addStorageMedia( new MemcacheStorage('10.1.30.4') );
Cache::addStorageMedia( new MemcacheStorage('10.1.30.5') );

Important: HybridCache doesn't support HA (High Availability) methods in this scenario yet. We expect to implement failover mechanisms on future versions.

Multiple array philosophy

In future versions we're planning to implement groups of arrays that can combine the efficency of scalability with the fault tolerance of replication.

Who use it??

DePaginas

Website with several sections, web directory, classifieds, news and more

http://depaginas.com.ar

Periodico Tribuna

Argentinan digital newspaper

http://periodicotribuna.com.ar/

uWall.tv

Best artist listed in a wall format. Just pick an artist and discover a new experience :)

http://uWall.tv

Taggify

Ad network with improvents and creatives products.

http://taggify.net

                                               README fixed by Andres Gattinoni
                                               http://www.tail-f.com.ar/

hybridcache's People

Contributors

exos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

hybridcache's Issues

PHP Notice: Undefined index: HOST

When hybrid cache is run under CLI, try define the default prefix by the host name (webserver param) and this don't exist.

The line is:

        $this->_prefix      = defined('CACHE_PREFIX') ? CACHE_PREFIX            : $_SERVER['HOST'];

End the error:

PHP Notice:  Undefined index: HOST in /home/exos/alpha/HybridCache/lib/hybrid/cache.php on line 133

new Cache and Cache::create shred identified

A cache instance created by new Cache is diferent of Cache::create with the same parameters.

This change do it is equal.

$cache = new Cache ('dsfsd',34);

Equal that

$cache = Cache::create ('dsfsd',34);

Add composer

Add composer to easy way install as dependency.

Avoid long connections in the middle storages

When the cache is used, connect the storages mean that you will use (if required connection), if the cache is used a second time and the process takes, these connections are alive and can cause exess connections to storage.

To avoid this you must implement an option that allows the closing of connections between uses of storage medias.

Add method getCacheOr to easy usage.

Add a method with a callback to generate the cache, for easy and fast implement on classes or pages.

return $Cache->getCacheOr('tagid', function () {
         $res = $db->query();
         ...
         return $res;
} );

Add MySQL support

Create MySQL connector as Storage Media for cache in sites without other tecnologies support.

Implement an Object Pool

Implement an Object Pool for reusage instances on a complex scripts, like large execution CLI scipts.

std Object as array: Error on addStorage method

Triying use clearStorages and addStorage method on an instance throw this error. Explain:

The public function addStorage isn't saving with $for arguments, and try add an object on the array of storages medias:

public function addStorage(StorageMedia $storage) {
    $this->_storages = (object) array(
        'connected' => false,
        'store' => $storage
    );
}

When the static method (works) use the $for argument as key of first array:

self::$_prestorages[self::FOR_READ] = .....

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.