Save items in a bucket, retrieve them later.

Related tags

Miscellaneous Bucket
Overview

Bucket

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

Save items in a bucket, retrieve them later.

use Laragear\Bucket\Facades\Buckets;
use App\Models\Message;

public function send(Message $message)
{
    $bucket = Buckets::get($message->receiver)->add($message)->save();
    
    if ($bucket->isNew()) {
        $message->receiver->notify(new MessagesReceived($bucket))->delay(300);
    }
}

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

Installation

You can install the package via Composer:

composer require laragear/bucket

Usage

A bucket is like a living box where you add items that persist across requests. You interact with Buckets mainly using the Buckets facade.

Start creating one Bucket using get() with a unique key to identify it. Once you add items using add(), you may save the bucket using save(), otherwise it will be done automatically once destroyed.

use Laragear\Bucket\Facades\Buckets;
use App\Models\Message;

public function send(Message $message)
{
    // Save the message into the bucket for the receiver ID.
    Buckets::get($message->receiver)->add($message)->save();
}

You can later retrieve the same bucket and its items using the Bucket facade and the get method, along with its identifier.

use Laragear\Bucket\Facades\Buckets;
use App\Models\Message;
use App\Models\User;

public function received(User $receiver)
{
    // Show all messages receives so far.
    $messages = Buckets::get($receiver)->items();
}

Key helpers

While you may use a simple string to identify a Bucket, you can just use a Model, Request or Session instance as a keys:

  • A Model will use its class name and primary key.
  • A Request will use its fingerprint.
  • A Session will use its identifier.
use Laragear\Bucket\Facades\Buckets;
use \Illuminate\Http\Request;
use App\Models\Message;
use App\Models\User;

public function received(Request $request, User $receiver)
{
    // Use the request fingerprint.
    Buckets::get($request);
    
    // Use the user session.
    Buckets::get($request->session());
    
    // Use a particular model instance.
    Buckets::get($receiver);
    
    // ...
}

Adding items

A Bucket uses a Collection underneath to save each item added to it. After adding them, you can retrieve them all using items().

use Laragear\Bucket\Facades\Buckets;

$bucket = Buckets::get('messages')->add('Hello!');

$bucket->add('World!');

$bucket->items(); // ["Hello!", "World!"]

Changes made to the items directly will not propagate to the Bucket instance. You may want to use save(true) on the bucket to force saving any changes.

All the items in the Collection will be serialized when cached. For the case of Eloquent Models, a Bucket will intelligently use an Eloquent Collection if your first item is an Eloquent Model, or an Eloquent Collection itself. This will allow the Bucket to serialize the model identifiers so these can be retrieved later, optimizing the cache storage.

use Laragear\Bucket\Facades\Buckets;
use App\Model\Message;

$messages = Message::where('is_read', false)->get();

$bucket = Buckets::get('messages')->add($messages)->save();

For further optimizations, you can add withoutRelations() to unload the Model relations before adding them to the Bucket.

On create callback

Add a callback to the created() method, which will save the bucket and execute the callback only if it's new in the cache.

use Laragear\Bucket\Facades\Buckets;
use App\Notificationes\MessagesReceived;

public function received(User $receiver)
{
    Buckets::get($message->receiver)
        ->add($message)
        ->created(function ($bucket) use ($message) {
            // This bucket is new. Capture all messages for 5 minutes.
            $message->receiver->notify((new MessagesReceived($bucket))->delay(60 * 5));
        });
}

Deleting a bucket

After you're done with a Bucket, you can remove it from the cache using delete() from the Bucket instance itself.

use Laragear\Bucket\Facades\Buckets;

public function received(User $receiver)
{
    $bucket = Buckets::get($receiver);
    
    // ...
    
    $bucket->delete();
}

Alternatively, you may want to use pull() instead, which retrieves the Bucket from the Cache and forgets it in one method.

use Laragear\Bucket\Facades\Buckets;

public function received(User $receiver)
{
    $bucket = Buckets::pull($receiver);
    
    // ...
}

Lifetime

Bucket are persisted for a default of 15 minutes, which is the same maximum minutes to delay a Queued Job in Amazon SQS. You can set a Bucket with your own expiration time, or use forever() to keep it until the end of time.

use Laragear\Bucket\Facades\Buckets;

public function received(User $receiver)
{
    // Add an expiration time.
    Buckets::get($receiver)->expireAt(60 * 5);
    
    // Remember it forever
    Buckets::get($receiver)->forever();
}

Fresh instance

Sometimes you may have edited the bucket elsewhere, making the current instance stale. For these occasions, you can use fresh(), which will return a new fresh instance from the Cache.

use Laragear\Bucket\Facades\Buckets;

$bucket = Buckets::get($receiver)->add($message)->save();

// ...

$fresh = $bucket->fresh();

Advanced configuration

Bucket is intended to work out-of-the-box, but you can publish the configuration file for changing its defaults.

php artisan vendor:publish --provider="Laragear\Bucket\BucketServiceProvider" --tag="config"

You will get the bucket.php config file with this array:

<?php

return [
    'store' => null,
    'ttl' => 15 * 60,
    'prefix' => 'bucket',
];

Cache store

return [
    'store' => null,
];

The default cache store to use for handling Buckets. If null, it will use the application default.

You can override this at runtime using the store() method of the Buckets facade.

use Laragear\Bucket\Facades\Buckets;

Buckets::store('redis')->get('my_bucket');

Time-to-live

return [
    'ttl' => 15 * 60,
];

The default amount of time in seconds that each Bucket should live in the cache. When null, these will live forever.

Prefix

return [
    'prefix' => 'bucket',
];

The cache key prefix to use when storing buckets into the Cache. You may change it to avoid risks of collision with other cache keys.

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...
Track any ip address with IP-Tracer. IP-Tracer is developed for Linux and Termux. you can retrieve any ip address information using IP-Tracer.
Track any ip address with IP-Tracer. IP-Tracer is developed for Linux and Termux. you can retrieve any ip address information using IP-Tracer.

IP-Tracer is used to track an ip address. IP-Tracer is developed for Termux and Linux based systems. you can easily retrieve ip address information using IP-Tracer. IP-Tracer use ip-api to track ip address.

The swiss army knife for Magento developers, sysadmins and devops. The tool provides a huge set of well tested command line commands which save hours of work time. All commands are extendable by a module API.

netz98 magerun CLI tools for Magento 2 The n98 magerun cli tools provides some handy tools to work with Magento from command line. Build Status Latest

#️⃣  Generate, Save, and Route Stripe-like Hash IDs for Laravel Eloquent Models
#️⃣ Generate, Save, and Route Stripe-like Hash IDs for Laravel Eloquent Models

Using this package you can generate, save and, route Stripe-like Hash Ids for your Eloquent Models. Hash Ids are short, unique, and non-sequential, an

now you can save MentionedMessage in UI
now you can save MentionedMessage in UI

General now you can save MentionedMessage in UI Example: You Chat Hi @MulqiGaming @Friends it will be save Message later to MulqiGaming and Friends Co

Library download currency rate and save in database, It's designed to be extended by any available data source.

Library download currency rate and save in database, It's designed to be extended by any available data source.

Magento 2 module to automatically flush the cache whenever you save something in the System Configuration

Yireo AutoFlushCache Magento 2 module to automatically flush the cache whenever you save something in the System Configuration. Do NOT use this in pro

Plugin to add items
Plugin to add items

CustomItem Plugin to add items No more item limit 💫 Your imagnition the only barrier 💭 New id new items 🔢 How to make texture for new item 1• Creat

Add custom armors, tools and many items!

CustomThings This plugin was created for the new version of Hiroshima and allows you to add tools, armors and items! Informations Here are the differe

PocketMine-MP plugin that inhibits players from dropping items.

PocketMine-MP plugin that inhibits players from dropping items. This plugin also comes with a variety of useful commands.

Releases(v1.1.1)
Owner
Laragear
Packages for Laravel
Laragear
Allow any Discord user to sign in to your website and save their discord user information for later use.

Simple Discord SSO ( Single Sign-On ) Requires at least: 5.0 Tested up to: 5.8.3 Stable tag: 1.0.2 Requires PHP: 7.4 License: GPLv2 or later License U

null 2 Oct 7, 2022
YCOM Impersonate. Login as selected YCOM user 🧙‍♂️in frontend.

YCOM Impersonate Login as selected YCOM user in frontend. Features: Backend users with admin rights or YCOM[] rights, can be automatically logged in v

Friends Of REDAXO 17 Sep 12, 2022
Implementation of the Token Bucket algorithm in PHP.

Token Bucket This is a threadsafe implementation of the Token Bucket algorithm in PHP. You can use a token bucket to limit an usage rate for a resourc

null 477 Jan 7, 2023
This is a plugin for pocketmine-mp, when locking a player's items helps players not to lose items or throw things around causing server lag.

[] LockedItem| v1.0.0 Player's item lock Features Player's item lock Players aren't afraid of losing items For Devolopers You can access to LockedItem

JeroGamingYT 3 Jan 4, 2022
StickWithIt is an online food ordering website created using PHP. You can view and purchase various items as well as remove items from the cart.

StickWithIt (App Name) StickWithIt is an online food ordering website created using PHP. The database used here is MYSQL database. The tool used here

Jenil Gajjar 1 May 11, 2022
All about docker projects either from dockerfile or compose. Anyway, here the project is in the form of a service, for the programming language I will make it later

Docker Project by ItsArul Hey, yo guys okay, this time I made some projects from Docker. Anyway, this project is open source, for example, if you want

Kiyo 10 Nov 4, 2022
Disclaimer: The documentation of this plugin is English at the moment, but I might go for Latin later down the line, just for the fun of it.

Quiritibus Plugin This repository is storing the custom plugin developed for the Quiritibus Latin Magazine website, currently being developed at: http

Alkor András 1 Jan 19, 2022
Backwards compatibility Extension and Library for PHP 8.x and later

colopl_bc Provides various compatibility functions required for PHP (temporary) migration. WARNING This extension is intended for temporary use only.

COLOPL,Inc. 10 Jun 13, 2023
A script to retrieve data from a Netatmo weather station and display it in a Mac menu bar.

weathermenu A script to retrieve data from a Netatmo weather station and display it in a Mac menu bar. Intended for use with SwiftBar. Configuration N

Dan Moren 4 Nov 4, 2021
This library can be used, among other things, to retrieve the classes, interfaces, traits, enums, functions and constants declared in a file

marijnvanwezel/reflection-file Library that allows reflection of files. This library can be used, among other things, to retrieve the classes, interfa

Marijn van Wezel 5 Apr 17, 2022