• Stars
    star
    2,246
  • Rank 20,499 (Top 0.5 %)
  • Language
    PHP
  • License
    MIT License
  • Created about 7 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Eloquent model-caching made easy.

Model Caching for Laravel

Laravel Package Scrutinizer BCH Compliance Coveralls GitHub (pre-)release Packagist GitHub license

Model Caching for Laravel masthead image

Supporting This Package

This is an MIT-licensed open source project with its ongoing development made possible by the support of the community. If you'd like to support this, and our other packages, please consider becoming a sponsor.

We thank the following sponsors for their generosity, please take a moment to check them out:

Impetus

I created this package in response to a client project that had complex, nested forms with many <select>'s that resulted in over 700 database queries on one page. I needed a package that abstracted the caching process out of the model for me, and one that would let me cache custom queries, as well as cache model relationships. This package is an attempt to address those requirements.

Features

  • automatic, self-invalidating relationship (only eager-loading) caching.
  • automatic, self-invalidating model query caching.
  • automatic use of cache tags for cache providers that support them (will flush entire cache for providers that don't).

Cache Drivers

This package is best suited for taggable cache drivers:

+ Redis
+ MemCached
+ APC
+ Array

It will not work with non-taggable drivers:

- Database
- File
- DynamoDB

Requirements

  • PHP 7.3+
  • Laravel 8.0+
    - Please note that prior Laravel versions are not supported and the package
    - versions that are compatible with prior versions of Laravel contain bugs.
    - Please only use with the versions of Laravel noted above to be compatible.

Possible Package Conflicts

Any packages that override newEloquentModel() from the Model class will likely conflict with this package. Of course, any packages that implement their own Querybuilder class effectively circumvent this package, rendering them incompatible.

The following are packages we have identified as conflicting:

Things That Don't Work Currently

The following items currently do no work with this package:

- caching of lazy-loaded relationships, see #127. Currently lazy-loaded belongs-to relationships are cached. Caching of other relationships is in the works.
- using select() clauses in Eloquent queries, see #238 (work-around discussed in the issue)
- using transactions. If you are using transactions, you will likely have to manually flush the cache, see [issue #305](https://github.com/GeneaLabs/laravel-model-caching/issues/305).

installation guide cover

Installation

Be sure to not require a specific version of this package when requiring it:

composer require genealabs/laravel-model-caching

Gotchas If Using With Lumen

The following steps need to be figured out by you and implemented in your Lumen app. Googling for ways to do this provided various approaches to this.

  1. Register the package to load in Lumen:
    $app->register(GeneaLabs\LaravelModelCaching\Providers\Service::class);
  2. Make sure your Lumen app can load config files.
  3. Publish this package's config file to the location your app loads config files from.

Upgrade Notes

0.6.0

The environment and config variables for disabling this package have changed.

  • If you have previously published the config file, publish it again, and adjust as necessary:

    php artisan modelCache:publish --config
  • If you have disabled the package in your .env file, change the entry from MODEL_CACHE_DISABLED=true to MODEL_CACHE_ENABLED=false.

0.5.0

The following implementations have changed (see the respective sections below):

  • model-specific cache prefix

Configuration

Recommended (Optional) Custom Cache Store

If you would like to use a different cache store than the default one used by your Laravel application, you may do so by setting the MODEL_CACHE_STORE environment variable in your .env file to the name of a cache store configured in config/cache.php (you can define any custom cache store based on your specific needs there). For example:

MODEL_CACHE_STORE=redis2

Usage

For best performance a taggable cache provider is recommended (redis, memcached). While this is optional, using a non-taggable cache provider will mean that the entire cache is cleared each time a model is created, saved, updated, or deleted.

For ease of maintenance, I would recommend adding a BaseModel model that uses Cachable, from which all your other models are extended. If you don't want to do that, simply extend your models directly from CachedModel.

Here's an example BaseModel class:

<?php namespace App;

use GeneaLabs\LaravelModelCaching\Traits\Cachable;

abstract class BaseModel
{
    use Cachable;
    //
}

Multiple Database Connections

Thanks to @dtvmedia for suggestion this feature. This is actually a more robust solution than cache-prefixes.

Keeping keys separate for multiple database connections is automatically handled. This is especially important for multi-tenant applications, and of course any application using multiple database connections.

Optional Cache Key Prefix

Thanks to @lucian-dragomir for suggesting this feature! You can use cache key prefixing to keep cache entries separate for multi-tenant applications. For this it is recommended to add the Cachable trait to a base model, then set the cache key prefix config value there.

Here's is an example:

<?php namespace GeneaLabs\LaravelModelCaching\Tests\Fixtures;

use GeneaLabs\LaravelModelCaching\Traits\Cachable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class BaseModel extends Model
{
    use Cachable;

    protected $cachePrefix = "test-prefix";
}

The cache prefix can also be set in the configuration to prefix all cached models across the board:

    'cache-prefix' => 'test-prefix',

Exception: User Model

I would not recommend caching the user model, as it is a special case, since it extends Illuminate\Foundation\Auth\User. Overriding that would break functionality. Not only that, but it probably isn't a good idea to cache the user model anyway, since you always want to pull the most up-to-date info on it.

Experimental: Cache Cool-down In Specific Models

In some instances, you may want to add a cache invalidation cool-down period. For example you might have a busy site where comments are submitted at a high rate, and you don't want every comment submission to invalidate the cache. While I don't necessarily recommend this, you might experiment it's effectiveness.

To use it, it must be enabled in the model (or base model if you want to use it on multiple or all models):

class MyModel extends Model
{
    use Cachable;

    protected $cacheCooldownSeconds = 300; // 5 minutes

    // ...
}

After that it can be implemented in queries:

(new Comment)
    ->withCacheCooldownSeconds(30) // override default cooldown seconds in model
    ->get();

or:

(new Comment)
    ->withCacheCooldownSeconds() // use default cooldown seconds in model
    ->get();

Disabling Caching of Queries

There are two methods by which model-caching can be disabled:

  1. Use ->disableCache() in a query-by-query instance.
  2. Set MODEL_CACHE_ENABLED=false in your .env file.
  3. If you only need to disable the cache for a block of code, or for non- eloquent queries, this is probably the better option:
    $result = app("model-cache")->runDisabled(function () {
        return (new MyModel)->get(); // or any other stuff you need to run with model-caching disabled
    });

Recommendation: use option #1 in all your seeder queries to avoid pulling in cached information when reseeding multiple times. You can disable a given query by using disableCache() anywhere in the query chain. For example:

$results = $myModel->disableCache()->where('field', $value)->get();

Manual Flushing of Specific Model

You can flush the cache of a specific model using the following artisan command:

php artisan modelCache:clear --model=App\Model

This comes in handy when manually making updates to the database. You could also trigger this after making updates to the database from sources outside your Laravel app.

Summary

That's all you need to do. All model queries and relationships are now cached!

In testing this has optimized performance on some pages up to 900%! Most often you should see somewhere around 100% performance increase.

Commitment to Quality

During package development I try as best as possible to embrace good design and development practices, to help ensure that this package is as good as it can be. My checklist for package development includes:

  • Achieve as close to 100% code coverage as possible using unit tests.
  • Eliminate any issues identified by SensioLabs Insight and Scrutinizer.
  • Be fully PSR1, PSR2, and PSR4 compliant.
  • Include comprehensive documentation in README.md.
  • Provide an up-to-date CHANGELOG.md which adheres to the format outlined at https://keepachangelog.com.
  • Have no PHPMD or PHPCS warnings throughout all code.

Contributing

Please observe and respect all aspects of the included Code of Conduct https://github.com/GeneaLabs/laravel-model-caching/blob/master/CODE_OF_CONDUCT.md.

Reporting Issues

When reporting issues, please fill out the included template as completely as possible. Incomplete issues may be ignored or closed if there is not enough information included to be actionable.

Submitting Pull Requests

Please review the Contribution Guidelines https://github.com/GeneaLabs/laravel-model-caching/blob/master/CONTRIBUTING.md. Only PRs that meet all criterium will be accepted.

If you ❤️ open-source software, give the repos you use a ⭐️.

We have included the awesome symfony/thanks composer package as a dev dependency. Let your OS package maintainers know you appreciate them by starring the packages you use. Simply run composer thanks after installing this package. (And not to worry, since it's a dev-dependency it won't be installed in your live environment.)

More Repositories

1

laravel-caffeine

Keeping Your Laravel Forms Awake.
PHP
921
star
2

laravel-sign-in-with-apple

Provide "Sign In With Apple" functionality to your Laravel app.
PHP
443
star
3

laravel-governor

Manage authorization with granular role-based permissions in your Laravel Apps.
PHP
183
star
4

laravel-messenger

Notifying your users doesn't have to be a lot of work.
PHP
135
star
5

nova-map-marker-field

Provides an visual interface for editing latitude and longitude coordinates.
Vue
131
star
6

laravel-mixpanel

Intuitive drop-in analytics.
PHP
117
star
7

laravel-pivot-events

PHP
114
star
8

nova-gutenberg

Implementation of the Gutenberg editor as a Laravel Nova Field based on Laraberg.
Vue
107
star
9

laravel-socialiter

Automatically manage user persistence and resolution for any Laravel Socialite provider.
PHP
101
star
10

laravel-casts

Form builder for Laravel.
PHP
93
star
11

laravel-maps

Easy - peasy - maps for Laravel
PHP
81
star
12

laravel-overridable-model

Provide a uniform method of allowing models to be overridden in Laravel.
PHP
63
star
13

nova-file-upload-field

The easiest drag-and-drop file uploading field for Laravel Nova.
Vue
53
star
14

laravel-multi-step-progressbar

Quickly implement a multi-step progress-bar in Laravel.
PHP
45
star
15

laravel-impersonator

Package to allow user-impersonation in your Laravel and Nova apps.
PHP
45
star
16

laravel-optimized-postgres

Implement all textual fields as `text` in Postgres databases.
PHP
41
star
17

laravel-null-carbon

Carbon null-class.
PHP
39
star
18

nova-prepopulate-searchable

A tool to allow BelongsTo searchable fields to be pre-populated with data
Vue
37
star
19

laravel-changelog

Easily integrate and display your changelog in your app.
PHP
37
star
20

laravel-appleseed

Prevent the pesky Apple Touch Icon error log entries.
PHP
30
star
21

Phpgmaps

Larvel 5 implementation of BIOSTALL/CodeIgniter-Google-Maps-V3-API-Library.
PHP
27
star
22

nova-passport-manager

Manage Passport clients and tokens from within Nova.
Vue
26
star
23

nova-multi-tenant-manager

Manage tenants and their settings in Laravel Nova.
Vue
21
star
24

interesting-packages-and-articles

List of packages and articles we are interested in using that fulfill specific needs.
17
star
25

nova-telescope

Integrate Laravel Telescope into Laravel Nova.
PHP
17
star
26

tailwind-mac-colors

Color palette and swatches for macOS's color picker.
16
star
27

php-coding-standards

Custom PHPCS sniffs that support all our coding standards.
Shell
15
star
28

action-reviewdog-phpstan

🐾 Run PHPStan with ReviewDog.
Shell
12
star
29

nova-horizon

Integrate Laravel Horizon into Laravel Nova.
PHP
10
star
30

laravel-registrar

PHP
9
star
31

laravel-tawk

Easily and quickly integrate Tawk.to LiveChat into your laravel app in under 5 minutes!
PHP
8
star
32

tailwindcss-sketch-design-system

An atomic design system for TailwindCSS implemented in Sketch.
CSS
8
star
33

cashier-paypal

Laravel Cashier-compatible billing for PayPal
PHP
7
star
34

panic-nova-intelephense.novaextension

JavaScript
6
star
35

laravel-dev-environment

A collection of scripts and tutorials to optimize your Laravel development environment.
Shell
6
star
36

laravel-imagery

Serve contextually optimized images to speed up page rendering and improve the user experience!
PHP
6
star
37

laravel-authorization-addons

Additional helper methods and blade directives to help with more complex authorization queries.
PHP
6
star
38

action-reviewdog-phpmd

🐾 Run PHP Mess Detector with ReviewDog.
Shell
5
star
39

awesome-laravel-ignition-plugins

A curated list of plugins for the Laravel Igniter error package.
5
star
40

documentation

Documentation for all our open-source packages.
CSS
4
star
41

laravel-cashier-braintree

PHP
4
star
42

laravel-whoops-atom

Open Whoops Stack Trace Files in Atom Editor.
PHP
3
star
43

laravel-codespaces-app-template

Template for creating Laravel apps in codespaces.
PHP
3
star
44

action-reviewdog-phpcs

Shell
3
star
45

bootstrap-css-grid-override

Update bootstrap 4 with native CSS-grid with graceful degradation.
CSS
3
star
46

credo

My beliefs on being.
2
star
47

SculptKeyboardMapping

Keyboard mapping for Microsoft Sculpt Keyboard on Mac using KeyRemap4MacBook
2
star
48

panic-nova-phpcs.novaextension

JavaScript
2
star
49

laravel-codespaces-package-template

Template for creating Laravel packages in codespaces.
PHP
2
star
50

bones-macros

useful form macros for Laravel's Blade template engine.
PHP
2
star
51

laravel-nova-morph-many-to-one

Drop-in package that adds a many-to-one (inverse of one-to-many) polymorphic relationship to Eloquent and Nova.
PHP
2
star
52

laravel-collection-macros

PHP
2
star
53

unity-heraldry-generator

Heraldic Generator created in Unity using C# with the goal of providing a common web and in-game mechanism for creating Coats of Arms.
C#
1
star
54

laravel-multi-tenant-manager

PHP
1
star
55

panic-nova-phpmd.novaextension

JavaScript
1
star
56

panic-nova-atom-keybindings

1
star
57

nova-prepopulate-searchable-old

A tool to allow BelongsTo searchable fields to be pre-populated with data.
Vue
1
star
58

laravel-two-way-attribute-casting

Perform attribute casting when saving Eloquent models to the database.
PHP
1
star