当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

laravel-model-caching

Eloquent model-caching made easy.
授权协议 MIT License
开发语言 PHP
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 公西姚石
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Model Caching for Laravel

Laravel Package

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.

Impetus

I created this package in response to a client project that had complex, nestedforms with many <select>'s that resulted in over 700 database queries on onepage. I needed a package that abstracted the caching process out of the modelfor me, and one that would let me cache custom queries, as well as cache modelrelationships. 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 (willflush 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 willlikely conflict with this package. Of course, any packages that implement theirown Querybuilder class effectively circumvent this package, rendering themincompatible.

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 Lumenapp. 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 configfiles 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 byyour Laravel application, you may do so by setting the MODEL_CACHE_STOREenvironment variable in your .env file to the name of a cache store configuredin config/cache.php (you can define any custom cache store based on yourspecific 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 willmean 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 thatuses Cachable, from which all your other models are extended. If youdon'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 robustsolution than cache-prefixes.

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

Optional Cache Key Prefix

Thanks to @lucian-dragomir for suggesting this feature! You can use cache keyprefixing to keep cache entries separate for multi-tenant applications. For thisit is recommended to add the Cachable trait to a base model, then set the cachekey 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 cachedmodels 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 itextends 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 highrate, and you don't want every comment submission to invalidate the cache. WhileI 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 incached 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 alsotrigger this after making updates to the database from sources outside yourLaravel app.

Summary

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

In testing this has optimized performance on some pages up to 900%! Most oftenyou 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 canbe. 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 outlinedat 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 aspossible. Incomplete issues may be ignored or closed if there is not enoughinformation 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 devdependency. Let your OS package maintainers know you appreciate them by starringthe 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 yourlive environment.)

  • 创建模型文件 php artisan make:model Article Laravel会在app目录下生成一个Article.php的模型文件。但是我们为了方便,一般会将模型文件放在Model目录下,所以需要在生成文件的时候指定命名空间 php artisan make:model Models/Article Laravel会自动生成Models目录和Article.php文件,如果你

  • <?php namespace Illuminate\Database\Eloquent; /** * 下面提到某些词的含义: * 1、覆盖: 在继承该类 \Illuminate\Database\Eloquent\Model 的自定义的模型类中, 定义一个同名 field,值不一样 */ abstract class Model1 implements ArrayAcce

  •   随机查询 $data=Move::where('release',1) ->where('is_hot',1) ->where('is_status',1) ->orderBy(\DB::raw('RAND()')) ->take(4) ->get();   1.ORM操作需要创建对应的model          class User extends 

  • model 基本方法 “` $orders = App\Models\TestModel::all(); foreach ( ordersas o r d e r s a s order) { $order->users->get();} 如果一个订单有25个用户,将导致有26条SQL语句,使用with可解决这个问题 Book::with(‘user’)->get(); Book::with(‘a

  • php artisan make:model Article php artisan make:model Page root@cy-VirtualBox:/var/www/html/laravel5.0# php artisan make:model Article PHP Warning:  Module 'PDO' already loaded in Unknown on line 0 P

  • 1. Eloquent ORM(对象关系模型)     laravel 自带的, 提供了一个美观的、简单的连接数据库数据库ActiveRecord实现,每张数据表都对应一个与该表交互的“Model模型”,模型允许在表中进行查询,插入,更新和删除操作 2.AR:ActiveRecord(活动记录):       是一种领域模型模式,特点是一个模型类对应关系型数据库汇总的一个表,而模型类的一个实例对应

  • laravel自动生成model   laravel自动生成model 添加PHP扩展 composer require krlove/eloquent-model-generator --dev config/app注册GeneratorServiceProvider类 'providers' => [ // ... Krlove\EloquentModelGenerator\P

  • namespace App\Models\Demand; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; class DemandModel extends Model { protected $table = 'demand'; /** * 依据条件获取项目 * @param

  • 注意:对数据的操作时,需要查看自己嗯.env文件里的默认数据库是否跟改为需要操作的目标数据库 一、创建model模型文件: php artisan make:model Home/Member 创建后的文件会放在app目录下的Models目录下 二、model文件关联数据库表: 如果需要关联的数据表的名称,不是model文件的复数,比如:model文件:member 表名:(members)、mo

  •         昨天想把自己博客的首页做一下缓存,达到类似于生成静态页缓存的效果,在群里问了大家怎么做缓存,都挺忙的没多少回复,我就自己去看了看文档,发现了Caching这个部分,其实之前也有印象,但是没具体接触过,顾名思义,就是缓存了,那肯定和我的需求有点联系,我就认真看了看,发现的确是太强大了,经过很简单的几个步骤,我就改装好了首页,用firebug测试了一下,提高了几十毫秒解析时间,当然了有

  • 一.查询构建器的get方法 查询构建器的get方法返回了一个集合 $users = App\User::where('active', 1)->get(); foreach ($users as $user) { echo $user->name; } 二.访问器&调整器 1.访问器:为数据库的某列在用属性读取的时候做处理 class User extends Model{

  • namespace App\Models\Common; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; class CommonModel extends Model { /** * 创建 * @param String $table 表名 * @param

  • Authentication systems are a vital part of most modern applications, and should thus be appropriately implemented. In this article, you will learn how to build an authentication system using Vue.js an

  • 1、save() $bool = $model->save(); 返回 true 2、create()        单条或者批量,维护时间戳 $obj = $model->create($data); 返回 model 3、insert()        单条或者批量,不维护时间戳 $bool = $model->insert($data); 返回 bool 4、increments() / d

  • 一、时间显示 在模型内定义时间格式,否则model返回 "2020-08-13T03:36:53.000000Z"格式 <?php namespace App\Model; use Illuminate\Database\Eloquent\Model; use DateTimeInterface; class Models extends Model{ protected funct

  • 创建model:php artisan make:model privilegeModel(名字随便写,可以不加Model) 控制器层加载model <?php namespace App/Http/Controllers/Admin; //注意命名空间 use App/Http/Controllers/Controller; use App/privilegeModel; function in

  • 由于数据库表太多不想一个个创建基础的Model模板,所以就写了这个东东! 好了直接上代码把! namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; class CreateModelCommand extends Command { /** * The n

  • Laravel可以在Model设置字段默认值,之后在对Model赋值的时候,如果设置默认值的字段没有被显性赋值,框架就会自动填充默认值,并存入数据库中。 protected $attributes = [ 'status' => self::STATUS_UNCONFIRMED, 'role_id' => self::ROLE_PUBLISHER, ];

  • 1、设置默认属性返回值 protected $attributes = [ 'goal_distance' => '100', 'goal_time' => '0', 'reaction_force' => '0', 'handle_height' => '0' ]; 通过withDefault()当查询未空时返回上面数据

  • php artisan make:model Models/Category php artisan admin:make CategoryController --model=App\Models\Category 生成控制器 php artisan make:controller /User/ListController

 相关资料
  • Adding state behaviour to Eloquent models This package adds state support to models. It combines concepts from the state pattern and state machines. It is recommended that you're familiar with both pa

  • 本文向大家介绍laravel model 两表联查示例,包括了laravel model 两表联查示例的使用技巧和注意事项,需要的朋友参考一下 1对一 定义一对一关联 一对一关联是很基本的关联。例如一个 User 模型会对应到一个 Phone 。 在 Eloquent 里可以像下面这样定义关联: 传到 hasOne 方法里的第一个参数是关联模型的类名称。定义好关联之后,就可以使用 Eloquent

  • 获取模型 get 函数 public function get($columns = ['*']) { $builder = $this->applyScopes(); if (count($models = $builder->getModels($columns)) > 0) { $models = $builder->eagerLoadRelations($m

  • 前言 前面几个博客向大家介绍了查询构造器的原理与源码,然而查询构造器更多是为 Eloquent Model 服务的,我们对数据库操作更加方便的是使用 Eloquent Model。 本篇文章将会大家介绍 Model 的一些特性原理。 Eloquent Model 修改器 当我们在 Eloquent 模型实例中设置某些属性值的时候,修改器允许对 Eloquent 属性值进行格式化。如果对修改器不熟悉

  • 前言 在前两篇文章中,向大家介绍了定义关联关系的源码,还有基于关联关系的关联模型加载与查询的源码分析,本文开始介绍第三部分,如何利用关联关系来更新插入关联模型。 hasOne/hasMany/MorphOne/MorphMany 更新与插入 save 方法 正向的一对一、一对多关联保存方法用于对子模型设置外键值: public function save(Model $model) { $

  • 前言 数据库表通常相互关联。laravel 中的模型关联功能使得关于数据库的关联代码变得更加简单,更加优雅。本文会详细说说关于模型关联的源码,以便更好的理解和使用关联模型。官方文档:Eloquent:关联 定义关联 所谓的定义关联,就是在一个 Model 中定义一个关联函数,我们利用这个关联函数去操作另外一个 Model,例如,user 表是用户表,posts 是用户发的文章,一个用户可以发表多篇