Skip to content

A micro-package for a simple PHP key-value, cache-like store

License

Notifications You must be signed in to change notification settings

oconnedk/LightweightStore

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

LightweightStore

This simple micro-package defines a key-value store, with the main reason for existence being that it can serve as a run-time static method cache.

So, instead of repeatedly re-inventing a method static cache mechanism (see below), this can achieve the "is that thing in the cache?" "no? add it" "yes? use it" in one-or-two lines.

Build Status

Why?

Because copy-pasting/ regurgitating "patterns" is error prone, with gotchas lying within isset instead of array_key_exists etc.

So, instead of:

public function doSomethingWithAnId($id, $someOtherValue)
{
    static $cache = [];
    $thatThing = null;
    if (array_key_exists($id, $cache)) {
        $thatThing = $cache[$id];
    } else {
        $thatThing = new ThingThatWillTakeAWhile($id);
    }
    $thatThing->hereIs($someOtherValue);
}

You can do:

public function doSomethingWithAnId($id, $someOtherValue)
{
    $cache = LightweightStore::getStore(__METHOD__);
    $thatThing = $cache->get(
        $id,
        function ($key) {
            return new ThingThatWillTakeAWhile($key);
        }
    );
    $thatThing->hereIs($someOtherValue);
}

Semantically, that should hopefully be easy to understand. The second argument to ::get is a callable defining how to create that thing we want if it's not in our cache.

The use of ::getStore is not mandatory, but has the benefit of defining a scope which you can use to lock something down to a method, class, module or application if needs be.

Have a look at the unit tests for example use.

Installation

Composer Installation

See: Composer Installation

Edit composer.json:

"repositories": [
  {
    "type": "vcs",
    "url": "git@github.com:oconnedk/LightweightStore.git"
  }
],

Then:

composer require oconnedk/LightweightStore ^1.0 

Unit Tests

composer test

Coding Standard

All coding should comply with the PSR-2, enforced by PHPCS.

Checking for compliance:

composer psr2

About

A micro-package for a simple PHP key-value, cache-like store

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages