PHPackages                             eribloo/laravel-cache-objects - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. eribloo/laravel-cache-objects

ActiveLibrary[Caching](/categories/caching)

eribloo/laravel-cache-objects
=============================

Strongly typed cache objects

1.1.4(1y ago)023[5 PRs](https://github.com/EriBloo/laravel-cache-objects/pulls)MITPHPPHP ^8.2CI passing

Since Oct 15Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/EriBloo/laravel-cache-objects)[ Packagist](https://packagist.org/packages/eribloo/laravel-cache-objects)[ Docs](https://github.com/19932449-eribloo/laravel-cache-objects)[ GitHub Sponsors](https://github.com/EriBloo)[ RSS](/packages/eribloo-laravel-cache-objects/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (6)Dependencies (12)Versions (13)Used By (0)

Strongly typed cache objects
============================

[](#strongly-typed-cache-objects)

[![Latest Version on Packagist](https://camo.githubusercontent.com/2d3154bc7ccd2e5efc939bba2a7769a62bc1ba2240d32b8f27dc4b18184ef927/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f657269626c6f6f2f6c61726176656c2d63616368652d6f626a656374732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/eribloo/laravel-cache-objects)[![GitHub Tests Action Status](https://camo.githubusercontent.com/97de9522af5d1be002b1c539cc9335aebf3f48d3fe28b3f52048b7b22af68342/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f657269626c6f6f2f6c61726176656c2d63616368652d6f626a656374732f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/eribloo/laravel-cache-objects/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/94e8a922273e22b932fba88442f72150c06486ad356f25db1c19be9c44ad45e9/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f657269626c6f6f2f6c61726176656c2d63616368652d6f626a656374732f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/eribloo/laravel-cache-objects/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/b6f5de8d0ee2efb3655490b14372f34c06b3a9c8747fdea16abdfa4b0cf7ad9b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f657269626c6f6f2f6c61726176656c2d63616368652d6f626a656374732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/eribloo/laravel-cache-objects)

Introducing Laravel package that simplifies cache management by allowing you to encapsulate all details in one place. Improve your application cache maintanance with less raw strings and static typing.

```
/**
 * @implements CacheObject
 *
 * @method static self make(User $user)
 */
final readonly class SomeUserCache implements CacheObject
{
    /** @use CacheObjectActions */
    use CacheObjectActions;

    public function __construct(
        public User $user,
    ) {}

    public function key(): StringKey
    {
        $id = $this->user->getKey();

        return new StringKey("some-cache:$id");
    }

    public function ttl(): CarbonInterval
    {
        return CarbonInterval::minutes(15);
    }

    /**
     * @return SerializeTransformer
     */
    public function transformer(): SerializeTransformer
    {
        return new SerializeTransformer();
    }
}
```

You can later use this object to interract with cache:

```
$user = User::findOrFail(1);

$key  = SomeUserCache::make($user)->store(now());  // 'some-cache:1'
$date = SomeUserCache::make($user)->retrieve();    // App\Support\Carbon object
$bool = SomeUserCache::make($user)->delete();      // true
```

Table of contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Usage](#usage)
    - [Creating](#creating)
    - [CacheObject](#cacheobject)
    - [Key](#key)
        - [StringKey](#stringkey)
        - [HashedKey](#hashedkey)
    - [Time-to-live](#time-to-live)
    - [Transformer](#transformer)
        - [JsonTransformer](#jsontransformer)
        - [SerializeTransformer](#serializetransformer)
        - [EncryptedTransformer](#encryptedtransformer)
        - [GuardTransformer](#guardtransformer)
    - [Traits](#traits)
        - [CacheObjectActions](#cacheobjectactions)
    - [Driver](#driver)
        - [CacheDriver](#cachedriver)
    - [Events](#events)
        - [CacheObjectStored](#cacheobjectstored)
        - [CacheObjectRetrieved](#cacheobjectretrieved)
        - [CacheObjectMissed](#cacheobjectmissed)
        - [CacheObjectDeleted](#cacheobjectdeleted)
- [Extending](#extending)
- [PHPStan](#phpstan)
- [Testing](#testing)
- [Changelog](#changelog)
- [Contributing](#contributing)
- [Credits](#credits)
- [Licence](#license)

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require eribloo/laravel-cache-objects
```

You can publish the config file with:

```
php artisan vendor:publish --tag="cache-objects-config"
```

This is the contents of the published config file:

```
return [
    'namespace' => 'App\Cache',
];
```

Usage
-----

[](#usage)

### Creating

[](#creating)

You can create basic Cache Object by running Artisan Command:

```
php artisan make:cache-object SomeCacheObject
```

this will create class implementing `EriBloo\CacheObjects\Contracts\CacheObject` in namespace specified in config with some defaults for you to configure.

### CacheObject

[](#cacheobject)

`EriBloo\CacheObjects\Contracts\CacheObject` interface requires you to implement 3 methods:

```
public function key(): EriBloo\CacheObjects\Contracts\Key;
public function ttl(): Carbon\CarbonInterval;
public function transformer(): EriBloo\CacheObjects\Contracts\Transformer;
```

### Key

[](#key)

Key interface is a wrapper for Stringable interface responsible for preparing key for storage. Currently 2 options exist.

##### StringKey

[](#stringkey)

Basic key that accepts string.

```
public function key(): EriBloo\CacheObjects\ValueObjects\Keys\StringKey
{
    return new StringKey(key: 'some-cache');
}
```

##### HashedKey

[](#hashedkey)

Decorator for other keys that returns hashes key before storage. Accepts optional algorithm in constructor (`sha256` by default).

```
public function key(): EriBloo\CacheObjects\ValueObjects\Keys\HashedKey
{
    return new HashedKey(
        key: new StringKey('some-cache'),
        algo: 'md5',
    );
}
```

### Time-to-live

[](#time-to-live)

Defined with `Carbon\CarbonInterval`. Values that resolve to 0 or less seconds are considered to be stored forever.

### Transformer

[](#transformer)

Transformers are classes responsible for modifying values before storage and after retrieval.

##### JsonTransformer

[](#jsontransformer)

Uses `json_encode` on save and `json_decode` on load. Accepts optional flags and depth in constructor.

```
public function transformer(): EriBloo\CacheObjects\ValueObjects\Values\JsonTransformer
{
    return new JsonTransformer(
        loadFlags: JSON_INVALID_UTF8_SUBSTITUTE,
        saveFlags: JSON_UNESCAPED_UNICODE,
        depth: 256,
    );
}
```

##### SerializeTransformer

[](#serializetransformer)

Transformer that uses PHP `serialize` on save and `unserialize` on load. Accepts optional `class-string[]|bool` in constructor to specify classes allowed for deserialization.

```
public function transformer(): EriBloo\CacheObjects\ValueObjects\Values\SerializeTransformer
{
    return new SerializeTransformer(allowedClasses: [SomeClass::class]);
}
```

##### EncryptedTransformer

[](#encryptedtransformer)

Decorator for other transformer that uses `Crypt::encryptString` on save and `Crypt::decryptString` on load.

```
public function transformer(): EriBloo\CacheObjects\ValueObjects\Values\EncryptedTransformer
{
    return new EncryptedTransformer(
        transformer: new SerializeTransformer,
    );
}
```

##### GuardTransformer

[](#guardtransformer)

Proxy for other transformer that doesn't modify values, but instead validates them before storage or after retrieval. This class accepts up to 2 closures that should throw an Exception when provided value is invalid.

```
public function transformer(): EriBloo\CacheObjects\ValueObjects\Values\GuardTransformer
{
    return new GuardTransformer(
        transformer: new EncryptedTransformer(new SerializeTransformer),
        onSaveGuard: function (CarbonInterface $value) {
            if ($value->isPast()) {
                throw new UnexpectedValueException;
            }
        },
        onLoadGuard: null,
    );
}
```

### Traits

[](#traits)

##### CacheObjectActions

[](#cacheobjectactions)

Optional (but helpful) trait that adds usage methods:

```
public static function make(): static; // easier creation
public function store(mixed $value): string; // put into storage, returns key stored in cache
public function retrieve(): mixed; // get from storage
public function delete(): bool; // remove from storage
protected function resolveDriver(): EriBloo\CacheObjects\Contracts\Driver; // resolves to default driver from Service Provider, more below
```

### Driver

[](#driver)

This interface defines methods used for interacting with storage. Currently 1 class exists.

##### CacheDriver

[](#cachedriver)

This class is a default driver that accepts an instance of `Illuminate\Contracts\Cache\Store`. Binding defined in Service Provider resolves this to your default cache storage.

### Events

[](#events)

Default driver dispatches events:

##### CacheObjectStored

[](#cacheobjectstored)

When object is put in storage.

```
final class CacheObjectStored
{
    public function __construct(
        public CacheObject $cacheObject,
        public mixed $originalValue,
        public string $transformedValue,
    ) {}
}
```

##### CacheObjectRetrieved

[](#cacheobjectretrieved)

When object is retrieved from storage.

```
final class CacheObjectRetrieved
{
    public function __construct(
        public CacheObject $cacheObject,
        public string $originalValue,
        public mixed $transformedValue,
    ) {}
}
```

##### CacheObjectMissed

[](#cacheobjectmissed)

When cache object retrieval misses.

```
final class CacheObjectMissed
{
    public function __construct(
        public CacheObject $cacheObject,
    ) {}
}
```

##### CacheObjectDeleted

[](#cacheobjectdeleted)

When cache object is removed from storage.

```
final class CacheObjectDeleted
{
    public function __construct(
        public CacheObject $cacheObject,
    ) {}
}
```

Extending
---------

[](#extending)

I created this package with ease of configuration in mind so you can easly create `Key`, `Transformer` or `Driver` that will suit your needs. Additionally if you have any ideas of classes that could be incorporated into main package feel free to open an Issue or Pull Request.

PHPStan
-------

[](#phpstan)

While I omited most of static typing in examples above for clarity, this package is developed with level 8 of PHPStan and parts of code that are working with `mixed` values (transformers, cache object interface and cache object action) are built with generics.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

All contributions are welcome.

Credits
-------

[](#credits)

- [EriBloo](https://github.com/eribloo)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance68

Regular maintenance activity

Popularity6

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 86.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

6

Last Release

571d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/72dd6cdd926e56d3f5372c97f485a719ddc38d8cffcb681f593be7d634da81fd?d=identicon)[eribloo](/maintainers/eribloo)

---

Top Contributors

[![EriBloo](https://avatars.githubusercontent.com/u/19932449?v=4)](https://github.com/EriBloo "EriBloo (46 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (4 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (3 commits)")

---

Tags

cachelaravelphpphplaravelcacheEriBloolaravel-cache-objects

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleECS

### Embed Badge

![Health badge](/badges/eribloo-laravel-cache-objects/health.svg)

```
[![Health](https://phpackages.com/badges/eribloo-laravel-cache-objects/health.svg)](https://phpackages.com/packages/eribloo-laravel-cache-objects)
```

###  Alternatives

[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.2M51](/packages/spatie-laravel-responsecache)[awssat/laravel-visits

Laravel Redis visits counter for Eloquent models

975163.6k2](/packages/awssat-laravel-visits)[swayok/alternative-laravel-cache

Replacements for Laravel's redis and file cache stores that properly implement tagging idea. Powered by cache pool implementations provided by http://www.php-cache.com/

202541.1k6](/packages/swayok-alternative-laravel-cache)[ryangjchandler/blade-cache-directive

Cache chunks of your Blade markup with ease.

202200.8k2](/packages/ryangjchandler-blade-cache-directive)[yediyuz/laravel-cloudflare-cache

laravel-cloudflare-cache

28239.2k](/packages/yediyuz-laravel-cloudflare-cache)[dragon-code/laravel-cache

An improved interface for working with cache

6844.8k10](/packages/dragon-code-laravel-cache)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
