Refresh items in your cache without data races.

Related tags

Caching CacheRefresh
Overview

Cache Refresh

Latest Version on Packagist Latest stable test run Codecov coverage Maintainability Sonarcloud Status Laravel Octane Compatibility

Refresh items in your cache without data races.

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Collection;
use App\Models\Message;

public function send(Message $message)
{
    Cache::refresh(
        $message->to, 
        fn ($messages) => Collection::wrap($messages)->push($message)
    );
}

Keep this package free

Your support allows me to keep this package free, up-to-date and maintainable. Alternatively, you can spread the word!

Requirements

  • Laravel 9.x, or later
  • PHP 8.0 or later
  • Cache Driver with Lock support (*).

Warning You can still use Cache Refresh without a driver that supports locking, but bear in mind, refreshing won't be atomic.

Installation

You can install the package via Composer:

composer require laragear/cache-refresh

Usage

Cache Refresh will retrieve a key value from your cache store that you can edit using a callback. This callback is free to change the value and return it to be persisted.

When the cached value doesn't exist, like when is first called, you will receive null, so remember to un-null the value when is first called.

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Collection;
use App\Models\Message;

public function send(Message $message)
{
    // Add the incoming message to a list of messages, refreshing the overall list.
    $messages = Cache::refresh(
        $message->to,
        function (?Collection $messages) use ($message) {
            return Collection::wrap($messages)->push($message);
        },
        60 * 5
    );
    
    return 'Messages has been queued';
}

Custom Expiration time

The callback also receives an Expire instance, which will allow you to change the expiration time of the key inside the callback.

use Illuminate\Support\Facades\Cache;
use Laragear\CacheRefresh\Expire;
use App\Models\Mission;

Cache::refresh('mission', function ($mission, Expire $expire) {
    $mission ??= new Mission();
    
    if ($mission->ongoing()) {
        // Set a new expiration time.
        $expire->at(today()->endOfDay());
    }
    
    if ($mission->completed()) {
        // Expire the value immediately.
        $expire->now();
    }
    
    if ($mission->isVeryDifficult()) {
        // Put it forever.
        $expire->never();
    }

    return $mission;
}, 60 * 5);

Custom Lock configuration

You can omit a callback to manage the lock time and the waiting time using lock() and waitFor(), respectively, and issue the callback using put().

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Collection;
use App\Models\Message;

Cache::refresh('mission')->lock(60)->waitFor(10)->put(fn ($value) => ..., 60 * 5);

PhpStorm stubs

For users of PhpStorm, there is a stub file to aid in macro autocompletion for this package. You can publish them using the phpstorm tag:

php artisan vendor:publish --provider="Laragear\CacheRefresh\CacheRefreshServiceProvider" --tag="phpstorm"

The file gets published into the .stubs folder of your project. You should point your PhpStorm to these stubs.

Laravel Octane compatibility

  • There are no singletons using a stale application instance.
  • There are no singletons using a stale config instance.
  • There are no singletons using a stale request instance.

There should be no problems using this package with Laravel Octane.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

License

This specific package version is licensed under the terms of the MIT License, at time of publishing.

Laravel is a Trademark of Taylor Otwell. Copyright © 2011-2022 Laravel LLC.

You might also like...
: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

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

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

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

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

Simple cache

Simple cache

Elephant - a highly performant PHP Cache Driver for Kirby 3

🐘 Kirby3 PHP Cache-Driver Elephant - a highly performant PHP Cache Driver for Kirby 3 Commerical Usage Support open source! This plugin is free but i

An improved helper for working with cache

Laravel Cache Installation To get the latest version of Laravel Cache, simply require the project using Composer: $ composer require dragon-code/larav

Comments
  • Improve CI

    Improve CI

    • :zero: Byte-level
      • Look for non-ASCII characters (non-English alphabets, whitespace characters, control characters)
    • :one: Syntax errors
      • Check source code for syntax errors
    • :two: Run unit and functional tests
    • :three: Static Analysis
      • Run static analysis: PHPStan
    • :four: Coding Standards
      • Check coding style
      • Adhere to EditorConfig
    opened by szepeviktor 18
  • Stop ignoring existing files

    Stop ignoring existing files

    From https://github.com/Laragear/CacheRefresh/commit/2154695141179135f5fe8db0b8c695fc298cf025

    Here is how to check for these files: git ls-files | git check-ignore --stdin --no-index

    opened by szepeviktor 2
Releases(v1.0.2)
Owner
Laragear
Packages for Laravel
Laragear
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
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
A fast, lock-free, shared memory user data cache for PHP

Yac is a shared and lockless memory user data cache for PHP.

Xinchen Hui 815 Dec 18, 2022
Distributed PSR-16 cache implementation for PHP 6 that uses browser cookies to store data

cookiecache Cache beyond the edge with cookies! This library provides a distributed PSR-16 compatible cache implementation for PHP 6 that uses browser

Colin O'Dell 8 Apr 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
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
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
DataLoaderPhp is a generic utility to be used as part of your application's data fetching layer to provide a simplified and consistent API over various remote data sources such as databases or web services via batching and caching.

DataLoaderPHP is a generic utility to be used as part of your application's data fetching layer to provide a simplified and consistent API over various remote data sources such as databases or web services via batching and caching.

Webedia - Overblog 185 Nov 3, 2022
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
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