GithubHelp home page GithubHelp logo

spatie / blink Goto Github PK

View Code? Open in Web Editor NEW
159.0 7.0 18.0 55 KB

Cache that expires in the blink of an eye

Home Page: https://spatie.be/open-source/packages

License: MIT License

PHP 100.00%
cache php blink

blink's Introduction

Cache that expires in the blink of an eye

Latest Version on Packagist run-tests Total Downloads

This package contains a class called Blink that can cache values. The cache only spans the length of a single request.

It can be used like this:

$blink = new Blink();

$blink->put('key', 'value');

$blink->get('key'); // Returns 'value'
$blink->get('prefix*'); // Returns an array of values whose keys start with 'prefix'

// once will only execute the given callable if the given key didn't exist yet
$expensiveFunction = function() {
   return rand();
});
$blink->once('random', $expensiveFunction); // returns random number
$blink->once('random', $expensiveFunction); // returns the same number

$blink->has('key'); // Returns true
$blink->has('prefix*'); // Returns true if the blink contains a key that starts with 'prefix'

// Specify a default value for when the specified key does not exist
$blink->get('non existing key', 'default') // Returns 'default'

$blink->put('anotherKey', 'anotherValue');

// Put multiple items in one go
$blink->put(['ringo' => 'drums', 'paul' => 'bass']);

$blink->all(); // Returns an array with all items

$blink->forget('key'); // Removes the item
$blink->forget('prefix*'); // Forget all items of which the key starts with 'prefix'

$blink->flush(); // Empty the entire blink

$blink->flushStartingWith('somekey'); // Remove all items whose keys start with "somekey"

$blink->increment('number'); // $blink->get('number') will return 1
$blink->increment('number'); // $blink->get('number') will return 2
$blink->increment('number', 3); // $blink->get('number') will return 5

// Blink implements ArrayAccess
$blink['key'] = 'value';
$blink['key']; // Returns 'value'
isset($blink['key']); // Returns true
unset($blink['key']); // Equivalent to removing the value

// Blink implements Countable
count($blink); // Returns 0
$blink->put('key', 'value');
count($blink); // Returns 1

If you want to use the same instance within the current request, you can use the static method global.

Blink::global()->put('key', 'value');

Blink::global()->get('key') // Returns 'value'

Read the usage section of this readme to learn the other methods.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/blink

Usage

A Blink instance can just be newed up.

$blink = new \Spatie\Blink\Blink()

You can call the following methods on it:

put

/**
 * Put a value in the blink cache.
 *
 * @param string|array $name
 * @param string|int|null $value
 *
 * @return $this
 */
public function put($name, $value = null)

get

/**
 * Get a value from the blink cache.
 *
 * This function has support for the '*' wildcard.
 *
 * @param string $name
 *
 * @return null|string
 */
public function get(string $name)

has

/*
 * Determine if the blink cache has a value for the given name.
 *
 * This function has support for the '*' wildcard.
 */
public function has(string $name) : bool

once

/**
 * Only if the given key is not present in the blink cache the callable will be executed.
 *
 * The result of the callable will be stored in the given key and returned.
 *
 * @param $key
 * @param callable $callable
 *
 * @return mixed
 */
public function once($key, callable $callable)

onceIf

/**
 * Use the "once" method only if the given condition is true.
 *
 * Otherwise, the callable will be executed.
 *
 * @param bool $shouldBlink
 * @param $key
 * @param callable
 *
 * @return mixed
 */
public function onceIf($shouldBlink, $key, callable $callable)

all

/*
 * Get all values in the blink cache.
*/
public function all() : array

allStartingWith

/**
 * Get all values from the blink cache which keys start with the given string.
 *
 * @param string $startingWith
 *
 * @return array
*/
public function allStartingWith(string $startingWith = '') : array

forget

/**
 * Forget a value from the blink cache.
 *
 * This function has support for the '*' wildcard.
 *
 * @param string $key
 *
 * @return $this
 */
public function forget(string $key)

flush

/**
 * Flush all values from the blink cache.
 *
 * @return $this
 */
 public function flush()

flushStartingWith

/**
 * Flush all values from the blink cache which keys start with the specified value.
 *
 * @param string $startingWith
 *
 * @return $this
 */
 public function flushStartingWith(string $startingWith)

pull

/**
 * Get and forget a value from the blink cache.
 *
 * This function has support for the '*' wildcard.
 *
 * @param string $name
 *
 * @return null|string
 */
public function pull(string $name)

increment

/**
 * Increment a value from the blink cache.
 *
 * @param string $name
 * @param int $by
 *
 * @return int|null|string
 */
 public function increment(string $name, int $by = 1)

decrement

/**
 * Decrement a value from the blink cache.
 *
 * @param string $name
 * @param int $by
 *
 * @return int|null|string
 */
 public function decrement(string $name, int $by = 1)

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Credits

We got the idea and the name for this package from Statamic's Blink helper. We reached out to them and got permission for using the blink name.

License

The MIT License (MIT). Please see License File for more information.

blink's People

Contributors

adamkelso avatar adrianmrn avatar chapeupreto avatar edalzell avatar freekmurze avatar jarlskov avatar jasonvarga avatar joecampo avatar patinthehat avatar sebastiandedeyne avatar sfinktah avatar shaffe-fr avatar stfndamjanovic avatar svenluijten 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

blink's Issues

Support for PHP 8.0?

First off, thanks so much for all the amazing packages you all make for the community.

I was wondering if this package was intended to be updated with support for PHP 8.0? Currently, it's locked on version 7. I would be happy to make a pull request, but do wonder what is your preferred way of handling PHPUnit. It's currently set to any version of v6 and v7. PHPUnit is currently on v9.

Thanks.

[Feature] Scoping

About

I've been wanting to contribute to some of your projects, and then I stumbled upon this nifty little package.

So after playing around with the API for a while I had a few different names for the feaure:

  • scope()/unscope()/scopeGroup()
    I find this a relevant word since this feature will be used to group entries by a prefix to isolate them from other keys that might be "out of scope".
  • focus()/unfocus()/focusGroup()
    Nice because can be "eye" related word-wise, and focusGroup is funny pun
  • prefix()/endPrefix()/prefixGroup()
    Describes exactly what it does, but feels clunky since the naming reminds me of writing a Blade directive instead of a cache related operation.

Any of the three names I would be satisfied with, so feel free to say if you'd like focus() or prefix() instead of scope() or something entirely different.

Before writing this PR I stumbled upon #2, which describes exactly this feature but my take on it U feel like is a bit more expressive.

Feature suggestion:

Here is what I've written in the docs on my branch:

Playground

blink()->scope('acme-'); // Prefix all key-related interactions with "acme-"
blink()->once('number', 3); // Sets key "acme-number" equal to 3
blink()->forget('key'); // Forgets key "acme-key"
blink()->unscope(); // Remove scope

blink()->scopeGroup('acme-', function() { // Prefix all key-related interactions with "acme-"
    blink()->once('number', 3); // Sets key "acme-number" equal to 3
    blink()->forget('key'); // Forgets key "acme-key"
});

Method signatures

scope

/**
 * Add prefix to all key-related interactions.
 *
 * @param string $prefix
 *
 * @return $this
 */
 public function scope(string $prefix)

unscope

/**
 * Remove currently active scope.
 *
 * @return $this
 */
 public function unscope()

scopeGroup

/**
 * Add prefix to all key-related interactions, within closure.
 *
 * @return $this
 */
 public function scopeGroup(string $prefix, callable $callback)

Support PHP 8.1

Using version 1.1.3, I'm seeing this in my logs, on PHP8.1:

CleanShot 2022-01-04 at 15 25 13@2x

Complex cache key wildcards not matching

Hello,
I'm using blink to dynamically cache fields from models and I'm using the full namespace as cache key.
The wildcards matching doesn't work because of the back-slashes.

A fix would be to use the FNM_NOESCAPE flag on the fnmatch function in the getKeysMatching method.

fnmatch('App\Models\Post|slug|id|*', 'App\Models\Post|slug|id|my-post'); // returns false
fnmatch('App\Models\Post|slug|id|*', 'App\Models\Post|slug|id|my-post', FNM_NOESCAPE); // returns true

Would you consider integrating this fix?

Regards,
Karel

[Feature] Conditional Once

Would you be open to a PR that would make the once method conditional?

We have a situation where we have some code inside a Blink::once closure, but sometimes we want to bypass it and just run the closure.

How about if you pass null/false as the $key, it just executes the closure?

It would allow us to change something like this:

$stuff = function () {
  // do stuff
};

if ($useBlink) {
  return $stuff();
} else {
  return Blink::once('foo', $stuff);
}

into this:

return Blink::once($useBlink ? 'foo' : null, function () {
  // do stuff
});

Or maybe a new method like onceIf if you don't want to change how once works:

return Blink::onceIf($useBlink, 'foo', function () {
  // do stuff
});

Numeric keys do not work

If you try to use a number (eg. an ID) as a key, it will not work. The array_merge resets the keys.

Here's a broken test:

    /** @test */
    function it_can_store_a_key_value_pair_with_a_numeric_key()
    {
        $this->blink->put('2', 'value');

        $this->assertSame('value', $this->blink->get('2'));
    }

I will try to PR it myself, but I thought if it looks simple to you then maybe you could handle it faster.

Thanks!

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.