LaraCache is an ORM based package for Laravel to create, update and manage cache items based on model queries

Related tags

Caching laravel cache
Overview

LaraCache

GitHub Workflow Status Codecov branch Quality Score GitHub license Packagist Downloads Latest Version on Packagist

Using this package, you can cache your heavy and most used queries.

All you have to do is to define the CacheEntity objects in the model and specify a valid name and ttl for them.

LaraCache will handle the rest of process automatically. It will create and update cache entities based on ttl that you've defined for each entity.

Manually updating the cache entities of models after dispatching model events (creating, updating and deleting) isn't required, LaraCache manages them in the background and ensures the most up-to-date version of each cache entity.


🚀 If you find this project interesting, please consider supporting me on the open source journey

Donate


Requirements:

  • PHP 8.0.2 or higher
  • Laravel 8.40.0 or higher

Installation

  1. Install the package via composer:
    composer require mostafaznv/laracache
  2. Publish config file:
    php artisan vendor:publish --provider="Mostafaznv\LaraCache\LaraCacheServiceProvider"
  3. Done

Usage

  1. Add LaraCache trait to the model
    <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use Mostafaznv\LaraCache\Traits\LaraCache;
    
    class Article extends Model
    {
        use LaraCache;
        
        /**
         * Define Cache Entities Entities
         *
         * @return CacheEntity[]
         */
        public static function cacheEntities(): array
        {
            return [
                CacheEntity::make('list.forever')
                    ->cache(function() {
                        return Article::query()->latest()->get();
                    }),
    
                CacheEntity::make('latest')
                    ->validForRestOfDay()
                    ->cache(function() {
                        return Article::query()->latest()->first();
                    })
            ];
        }
    }
  2. Retrieve Cache
    use App\Models\Article;
    use Mostafaznv\LaraCache\Facades\LaraCache;
    
    
    $cache = Article::cache()->get('latest');
    // or
    $cache = LaraCache::retrieve(Article::class, 'latest');

Table of Contents:

CacheEntity Methods

method Arguments description
setDriver driver (type: string) Specifies custom driver for cache entity
isQueueable status (type: bool, default: 'true') Specifies if cache operation should perform in the background or not
refreshAfterCreate status (type: bool, default: true) Specifies if the cache should refresh after create a record
refreshAfterUpdate status (type: bool, default: true) Specifies if the cache should refresh after update a record
refreshAfterDelete status (type: bool, default: true) Specifies if the cache should refresh after delete a record
refreshAfterRestore status (type: bool, default: true) Specifies if the cache should refresh after restore a record
forever Specifies that the cache should be valid forever
validForRestOfDay Specify that cache entity should be valid till end of day
validForRestOfWeek Specify that cache entity should be valid till end of week
ttl seconds (type: int) Specifies cache time to live in second
setDefault defaultValue (type: mixed) Specifies default value for the case that cache entity doesn't have any value
cache Closure Main part of each cache entity. defines cache content

Disable/Enable Cache

If you want to disable/enable cache, you can do it in the following two ways:

Disable

use App\Models\Article;
use Mostafaznv\LaraCache\Facades\LaraCache;


Article::cache()->disable();
// or 
LaraCache::disable(Article::class);

Enable

use App\Models\Article;
use Mostafaznv\LaraCache\Facades\LaraCache;


Article::cache()->enable();
// or 
LaraCache::enable(Article::class);

Update Cache Manually

Sometimes you want to update cache entities manually.

Update an Entity

use App\Models\Article;
use Mostafaznv\LaraCache\Facades\LaraCache;


Article::cache()->update('latest');
// or 
LaraCache::update(Article::class, 'latest');

Update all Entities

use App\Models\Article;
use Mostafaznv\LaraCache\Facades\LaraCache;


Article::cache()->updateAll();
// or 
LaraCache::updateAll(Article::class);

Update all LaraCache Entities

This will update all cache entities that stored using LaraCache (across all models)

use App\Models\Article;
use Mostafaznv\LaraCache\Facades\LaraCache;

 
LaraCache::updateAll();

Delete Cache Manually

Sometimes you want to delete cache entities manually. using these methods, you can do it.

Delete an Entity

Using this feature, you can delete cache entities temporary. after spending ttl, cache entity will be generated again.

use App\Models\Article;
use Mostafaznv\LaraCache\Facades\LaraCache;


Article::cache()->delete('latest');
// or 
LaraCache::delete(Article::class, 'latest');

Delete an Entity Forever

Using this feature, you can delete cache entities permanently. Cache item will be deleted forever and whenever you try to retrieve it, you will get null (or default value).

use App\Models\Article;
use Mostafaznv\LaraCache\Facades\LaraCache;


Article::cache()->delete('latest', true);
// or 
LaraCache::delete(Article::class, 'latest', true);

Note: Cache Entity will update after creating or updating records in your model

Delete all Model Entities

use App\Models\Article;
use Mostafaznv\LaraCache\Facades\LaraCache;


Article::cache()->deleteAll();
// or 
LaraCache::deleteAll(Article::class);

Delete all Model Entities Forever

use App\Models\Article;
use Mostafaznv\LaraCache\Facades\LaraCache;


Article::cache()->deleteAll(true);
// or 
LaraCache::deleteAll(Article::class, true);

Delete all LaraCache Entities

This will delete all cache entities that stored using LaraCache (across all models)

use App\Models\Article;
use Mostafaznv\LaraCache\Facades\LaraCache;

LaraCache::deleteAll();
// forever
LaraCache::deleteAll(forever: true);

Config Properties

method Type description
driver string (default: null) The default mechanism for handling cache storage.
If you keep this option null, LaraCache will use the default cache storage from config/cache.php
laracache-list string (default: laracache.list) LaraCache uses a separate list to store name of all entities. using these keys, we can perform some actions to all entities (such as update or delete them)
first-day-of-week integer (default: 0) In some regions, saturday is first day of the week and in another regions it may be different. you can change the first day of a week by changing this property
last-day-of-week integer (default: 6) In some regions, friday is last day of the week and in another regions it may be different. you can change the last day of a week by changing this property
queue bool (default: false) Sometimes caching process is very heavy, so you have to queue the process and do it in background.

Complete Example

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Mostafaznv\LaraCache\Traits\LaraCache;

class Article extends Model
{
    use LaraCache;
    
    /**
     * Define Cache Entities Entities
     *
     * @return CacheEntity[]
     */
    public static function cacheEntities(): array
    {
        return [
            CacheEntity::make('list.forever')
                ->forever()
                ->setDriver('redis')
                ->cache(function() {
                    return Article::query()->latest()->get();
                }),

            CacheEntity::make('list.day')
                ->isQueueable()
                ->validForRestOfDay()
                ->cache(function() {
                    return Article::query()->latest()->get();
                }),

            CacheEntity::make('list.week')
                ->validForRestOfWeek()
                ->cache(function() {
                    return Article::query()->latest()->get();
                }),

            CacheEntity::make('list.ttl')
                ->ttl(120)
                ->cache(function() {
                    return Article::query()->latest()->get();
                }),

            CacheEntity::make('latest')
                ->forever()
                ->cache(function() {
                    return Article::query()->latest()->first();
                }),

            CacheEntity::make('latest.no-create')
                ->refreshAfterCreate(false)
                ->cache(function() {
                    return Article::query()->latest()->first();
                }),

            CacheEntity::make('latest.no-update')
                ->refreshAfterUpdate(false)
                ->cache(function() {
                    return Article::query()->latest()->first();
                }),

            CacheEntity::make('latest.no-delete')
                ->refreshAfterDelete(false)
                ->cache(function() {
                    return Article::query()->latest()->first();
                }),

            CacheEntity::make('latest.no-restore')
                ->refreshAfterRestore(false)
                ->cache(function() {
                    return Article::query()->latest()->first();
                }),

            CacheEntity::make('empty.array')
                ->setDefault('empty value')
                ->cache(fn() => []),
        ];
    }
}

🚀 If you find this project interesting, please consider supporting me on the open source journey

Donate


License

This software is released under The MIT License (MIT).

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

More Than Just a Cache: Redis Data Structures
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

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
  • How often does this refresh the cache?

    How often does this refresh the cache?

    It is firing "Mostafaznv\LaraCache\Jobs\RefreshCache" event twice every second!!! My CPU usage is going high. Also, I used caching on only one model. Is it normal?

    image help wanted 
    opened by vins13pattar 4
  • Custom values?

    Custom values?

    How would you use the cache with custom values in a where clause, for example?

    <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use Mostafaznv\LaraCache\Traits\LaraCache;
    
    class Article extends Model
    {
        use LaraCache;
        
        /**
         * Define Cache Entities Entities
         *
         * @return CacheEntity[]
         */
        public static function cacheEntities(): array
        {
            return [
                CacheEntity::make('latest')
                    ->validForRestOfDay()
                    ->cache(function() {
                        return Article::query()->latest()->where('status', '[custom-status-here?]')->first();
                    })
            ];
        }
    }
    
    question 
    opened by dragonfire1119 2
Releases(2.1.0)
Owner
Mostafa Zeinivand
Mostafa Zeinivand
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
The cache component provides a Promise-based CacheInterface and an in-memory ArrayCache implementation of that

Cache Async, Promise-based cache interface for ReactPHP. The cache component provides a Promise-based CacheInterface and an in-memory ArrayCache imple

ReactPHP 330 Dec 6, 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
A simple cache library. Implements different adapters that you can use and change easily by a manager or similar.

Desarolla2 Cache A simple cache library, implementing the PSR-16 standard using immutable objects. Caching is typically used throughout an applicatito

Daniel González 129 Nov 20, 2022
A library providing platform-specific user directory paths, such as config and cache

Phirs A library providing platform-specific user directory paths, such as config and cache. Inspired by dirs-rs.

Mohammad Amin Chitgarha 7 Mar 1, 2022
A simple cache library. Implements different adapters that you can use and change easily by a manager or similar.

Desarolla2 Cache A simple cache library, implementing the PSR-16 standard using immutable objects. Caching is typically used throughout an applicatito

Daniel González 129 Nov 20, 2022
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
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
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
: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

Lars Moelleken 27 Dec 8, 2022