GithubHelp home page GithubHelp logo

lucmousinho / laravel-model-caching Goto Github PK

View Code? Open in Web Editor NEW

This project forked from mikebronner/laravel-model-caching

0.0 2.0 0.0 192 KB

Eloquent model-caching made easy.

License: MIT License

PHP 100.00%

laravel-model-caching's Introduction

pexels-photo-325229

Model Caching for Laravel

Gitter Travis Scrutinizer Coveralls GitHub (pre-)release Packagist GitHub license

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 (both eager- and lazy-loaded) 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).

Requirements

  • PHP >= 7.1.3
  • Laravel >= 5.5

installation guide cover

Installation

composer require genealabs/laravel-model-caching

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=redis

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;
    //
}

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.

Note that the config setting is included before the parent method is called, so that the setting is available in the parent as well.

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;

    public function __construct($attributes = [])
    {
        config(['genealabs:laravel-model-caching' => 'test-prefix']);

        parent::__construct($attributes);
    }
}

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.

Optional Disabling Caching of Queries

Recommendation: add this to all your seeder queries to avoid pulling in cached information when reseeding multiple times. You can disable a given query by using disableCache() in the query chain, and it needs to be placed (anywhere) prior to the query command (get(), all(), find(), etc). For example:

$results = $myModel->disableCache()->all();

Manual Flushing of Specific Model

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

php artisan modelCaching:flush --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 http://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.

❤️ Open-Source Software - Give ⭐️

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.)

laravel-model-caching's People

Contributors

allenjd3 avatar brunorsantos avatar fridzema avatar hanneskaeufler avatar lucmousinho avatar mikebronner avatar rs-sliske avatar sjbronner avatar smskin avatar vesper8 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.