PHPackages                             mrcache/mrcache - 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. mrcache/mrcache

ActiveLibrary[Caching](/categories/caching)

mrcache/mrcache
===============

A smart Redis caching layer for PHP frameworks Eloquent ORM.

4.0.0(7mo ago)637MITPHPPHP &gt;=8.2

Since Oct 7Pushed 7mo agoCompare

[ Source](https://github.com/mr-cache/mr-cache)[ Packagist](https://packagist.org/packages/mrcache/mrcache)[ RSS](/packages/mrcache-mrcache/feed)WikiDiscussions 4.x Synced 1mo ago

READMEChangelogDependencies (8)Versions (16)Used By (0)

MrCache for PHP frameworks
==========================

[](#mrcache-for-php-frameworks)

An advanced, native Redis caching layer for PHP frameworks Eloquent queries, bypassing the standard Laravel Cache facade for maximum performance and control.

[![PHP Tests](https://github.com/mr-cache/mr-cache/actions/workflows/php.yml/badge.svg)](https://github.com/mr-cache/mr-cache/actions/workflows/php.yml/badge.svg)[![Latest Version on Packagist](https://camo.githubusercontent.com/2cc1f5a99fc0c296a988cf61b4d6cb67cc96ab227af2d1ce0d3f400e154feef5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d7263616368652f6d7263616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mrcache/mrcache)[![Total Downloads](https://camo.githubusercontent.com/56abae89066d8ab6b1d8d5a182b3406a31c91d7862fd7ad0562d3508c1d7d4fd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d7263616368652f6d7263616368652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mrcache/mrcache)

---

[عرض التوثيق العربي](README_AR.md)

### 1. Introduction

[](#1-introduction)

"The difference between an ultra-fast MySQL database and one with mediocre performance often lies in the efficiency of its query cache management. Haphazard management can turn this feature into an obstacle. ​MrCache offers the optimal solution to this equation: an intelligent and automated management system that restores the power of your cache and ensures you get the most out of every query. Benefit from the power of smart automation, while retaining the ability to customize everything to fit your vision."

Most libraries that offer a caching layer for database queries—especially in the **PHP** environment, including for the **Laravel** framework—treat the cache like a naive notebook: they save a query to memory the first time it's called, then wipe everything clean at the first modification to the table! Update a row? Delete a record? Add new data? No problem, let's just drop the entire cache! But what's the point then? A database isn't just for reading; it's also for writing and modifying. The result is that the cache becomes a temporary visitor that doesn't live for more than a few moments, offering no real benefit. Instead, it adds overhead to the system with repeated write and delete operations. Worse yet, some of these libraries don't even give you the simplest forms of control—like setting a key's Time-To-Live (TTL). Why? **Because it makes no difference as long as the cache is constantly being cleared.**

This is where **MrCache** emerges as a mature exception in this landscape. It doesn't handle caching randomly but with intelligent management that understands the difference between data that has actually changed and data that hasn't been touched. When reading, **MrCache** first checks if the data exists in the cache:

- If it exists, it's returned immediately without any additional query to the database.
- If it doesn't exist, it acts intelligently:
- If the database returns no results, it stores nothing in the cache. An empty cache is a useless burden.
- If results are found, it checks if the query relies on the Primary Key to determine whether the result pertains to a single row or multiple rows.
- If the result is for a single row, it's stored in the unique rows section.
- If it's a general query, it's stored in the general queries section. When write operations occur, the real magic begins:
- If a specific row is modified via its Primary Key, only the cache for that specific row is invalidated—nothing more.
- If the modification affects more than one row, only the cache related to those rows is invalidated without touching others.
- If a new row is added, **MrCache** only invalidates general queries to update their results on subsequent calls. With this approach, **MrCache** maintains a delicate balance: the cached data remains constantly synchronized with the database without excessive invalidation or wasted memory. It's not just a caching intermediary but an intelligent cache management system designed specifically for MySQL queries—where performance is not sacrificed for accuracy, nor is accuracy lost in the name of speed.

### 1. Goal

[](#1-goal)

MrCache provides an automatic, highly configurable caching layer for your Eloquent models. It's designed to be "plug-and-play" with intelligent, granular cache invalidation. All queries are cached by default, giving you immediate performance gains.

### 2. Installation

[](#2-installation)

```
composer require mrcache/mrcache
```

Next, publish the configuration file:

```
php artisan vendor:publish --provider="MrCache\Providers\MrCacheServiceProvider" --tag="mrcache-config"
```

This will create a `config/mrcache.php` file where you can configure Redis connection, default TTL, and other settings.

### 3. Quick Start

[](#3-quick-start)

1. **Use the Trait:** Add the `CacheableModel` trait to any Eloquent model you want to cache.

    ```
    use Illuminate\Database\Eloquent\Model;
    use MrCache\Traits\CacheableModel;

    class Post extends Model
    {
        use CacheableModel;

        // Optional: Define a model-specific TTL in seconds
        protected $cacheTTL = 3600; // 1 hour

        // Optional: Define indexes
        protected $indexes = [
            ['col1'], // Single index
            ['col1', 'col2'], // Multiple index
        ];
    }
    ```
2. **That's it!** All queries for the `Post` model are now automatically cached.

    ```
    // First run: Hits the database and caches the result.
    $posts = Post::where('is_published', true)->get();

    // Second run (identical query): Fetches the result directly from Redis.
    $posts = Post::where('is_published', true)->get();
    ```

### 4. Advanced Usage

[](#4-advanced-usage)

#### Per-Query Control

[](#per-query-control)

You can control caching behavior on a per-query basis using fluent macros.

- **Disable Caching for a Query:**

    ```
    $uncachedPosts = Post::where('live_views', '>', 1000)->withoutCaching()->get();
    ```
- **Set a Custom TTL for a Query:**

    ```
    // Cache this specific result for only 60 seconds
    $breakingNews = Post::latest()->withCustomTTL(60)->first();
    ```

### 4.2 Relationships and Cascading Invalidation

[](#42-relationships-and-cascading-invalidation)

MrCache automatically invalidates cache for related models:

```
$author = Author::with('posts')->find(1);
$author->delete(); // invalidates the author AND all related posts
```

Works for:

- `hasOne` / `belongsTo`
- `hasMany` / `belongsToMany`
- Nested relationships

No manual listing of relationships required; MrCache inspects the Eloquent model.

---

### 4.3 Conditional Table/Row Invalidation

[](#43-conditional-tablerow-invalidation)

- Updates to a single row only invalidate queries that include that row.
- Mass updates or deletes with where conditions now automatically invalidate only the affected rows.

```
// Automatically invalidates cache for all rows where 'is_archived' = true
Post::where('is_archived', true)->update(['is_published' => false]);

// Similarly for mass deletes
Post::where('is_archived', true)->delete();
```

- ✅ No need to manually flush the cache for affected rows; MrCache handles it automatically.

### 5. Invalidation Rules

[](#5-invalidation-rules)

Invalidation is automatic and granular.

- **Single Row Invalidation:** When you update or delete a model instance, only the cache entries that include that specific row are invalidated.

    ```
    $post = Post::find(1); // Automatically stores cache for Post #1
    $post->title = 'New Title';
    $post->save(); // Automatically invalidates cache for Post #1
    ```
- **Mass Row Invalidation:** Mass updates or deletes via the query builder now automatically invalidate the cache for only the affected rows.

    ```
    // Automatically invalidates cache for all rows where 'is_archived' = true
    Post::where('is_archived', true)->update(['is_published' => false]);
    Post::where('is_archived', true)->delete();
    ```
- ✅ MrCache now ensures cache consistency for all affected rows, without manual flushes.

---

6. Artisan Commands
-------------------

[](#6-artisan-commands)

CommandDescription`php artisan mrcache:flush`Flush all cache`php artisan mrcache:flush --model="App\Models\Post"`Flush cache for a specific model/table`php artisan mrcache:flush --model="App\Models\Post" --pk=123`Flush a specific row`php artisan mrcache:stats`View cache hits/misses (requires metrics enabled)---

### 7. Configuration (`config/mrcache.php`)

[](#7-configuration-configmrcachephp)

```
