├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── composer.json ├── phpstan.neon.dist └── src ├── CacheableEloquent.php └── EloquentBuilder.php /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Rinvex Cacheable Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | This project adheres to [Semantic Versioning](CONTRIBUTING.md). 6 | 7 | 8 | ## [v5.0.1] - 2020-12-25 9 | - Add support for PHP v8 10 | 11 | ## [v5.0.0] - 2020-12-22 12 | - Upgrade to Laravel v8 13 | 14 | ## [v4.1.0] - 2020-06-15 15 | - Drop PHP 7.2 & 7.3 support from travis 16 | 17 | ## [v4.0.0] - 2020-03-15 18 | - Upgrade to Laravel v7.1.x & PHP v7.4.x 19 | 20 | ## [v3.0.1] - 2020-03-13 21 | - Tweak TravisCI config 22 | - Update StyleCI config 23 | 24 | ## [v3.0.0] - 2019-09-23 25 | - Upgrade to Laravel v6 and update dependencies 26 | 27 | ## [v2.1.0] - 2019-06-02 28 | - Update composer deps 29 | - Drop PHP 7.1 travis test 30 | 31 | ## [v2.0.2] - 2019-03-08 32 | - Bug fix: Replace fire function by dispatch (for real!) [close #27] 33 | 34 | ## [v2.0.1] - 2019-03-06 35 | - Bug fix: Replace fire function by dispatch 36 | 37 | ## [v2.0.0] - 2019-03-03 38 | - Rename environment variable QUEUE_DRIVER to QUEUE_CONNECTION 39 | - Require PHP 7.2 & Laravel 5.8 40 | 41 | ## [v1.0.1] - 2018-12-22 42 | - Update composer dependencies 43 | - Add PHP 7.3 support to travis 44 | 45 | ## [v1.0.0] - 2018-10-01 46 | - Enforce Consistency 47 | - Support Laravel 5.7+ 48 | - Rename package to rinvex/laravel-cacheable 49 | 50 | ## [v0.0.4] - 2018-09-22 51 | - Update travis php versions 52 | - Fix CacheableEloquent trait attributes overridability (fix #19) 53 | - Fix cache config defaults 54 | - Check cache directory existence 55 | - Drop StyleCI multi-language support (paid feature now!) 56 | - Update composer dependencies 57 | - Prepare and tweak testing configuration 58 | - Update StyleCI options 59 | - Update PHPUnit options 60 | 61 | ## [v0.0.3] - 2018-02-18 62 | - Update supplementary files 63 | - Update composer depedencies 64 | - Add Laravel 5.5 support 65 | - Support both eloquent and query builders 66 | - Cache plucked queries 67 | - Add PHPUnitPrettyResultPrinter 68 | - Typehint method returns 69 | - Fix wrong cache lifetime config after reset 70 | - Add Laravel v5.6 support 71 | - Tweak and enhance cacheable logic 72 | - Drop Laravel 5.5 support 73 | - Require PHP v7.1.3 74 | 75 | ## [v0.0.2] - 2017-03-14 76 | - Tweak and enhance forget cache mechanism 77 | - Update composer dependencies 78 | - Restrict compatibility to Laravel 5.4 79 | - Apply Laravel 5.4 event dispatcher updates 80 | - Facilitate flexible extension and overriding 81 | - Attach model cache tags and events to the original class, not lately static bound 82 | - Simplify code, this is tightly coupled package with Eloquent 83 | - Fix late static binding issues 84 | - Fix stupid gitattributes export-ignore issues 85 | 86 | ## v0.0.1 - 2017-01-18 87 | - Tag first release 88 | 89 | [v5.0.1]: https://github.com/rinvex/laravel-cacheable/compare/v5.0.0...v5.0.1 90 | [v5.0.0]: https://github.com/rinvex/laravel-cacheable/compare/v4.1.0...v5.0.0 91 | [v4.1.0]: https://github.com/rinvex/laravel-cacheable/compare/v4.0.0...v4.1.0 92 | [v4.0.0]: https://github.com/rinvex/laravel-cacheable/compare/v3.0.1...v4.0.0 93 | [v3.0.1]: https://github.com/rinvex/laravel-cacheable/compare/v3.0.0...v3.0.1 94 | [v3.0.0]: https://github.com/rinvex/laravel-cacheable/compare/v2.1.0...v3.0.0 95 | [v2.1.0]: https://github.com/rinvex/laravel-cacheable/compare/v2.0.2...v2.1.0 96 | [v2.0.2]: https://github.com/rinvex/laravel-cacheable/compare/v2.0.1...v2.0.2 97 | [v2.0.1]: https://github.com/rinvex/laravel-cacheable/compare/v2.0.0...v2.0.1 98 | [v2.0.0]: https://github.com/rinvex/laravel-cacheable/compare/v1.0.1...v2.0.0 99 | [v1.0.1]: https://github.com/rinvex/laravel-cacheable/compare/v1.0.0...v1.0.1 100 | [v1.0.0]: https://github.com/rinvex/laravel-cacheable/compare/v0.0.4...v1.0.0 101 | [v0.0.4]: https://github.com/rinvex/laravel-cacheable/compare/v0.0.3...v0.0.4 102 | [v0.0.3]: https://github.com/rinvex/laravel-cacheable/compare/v0.0.2...v0.0.3 103 | [v0.0.2]: https://github.com/rinvex/laravel-cacheable/compare/v0.0.1...v0.0.2 104 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at [help@rinvex.com](mailto:help@rinvex.com). All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guide 2 | 3 | This project adheres to the following standards and practices. 4 | 5 | 6 | ## Versioning 7 | 8 | This project is versioned under the [Semantic Versioning](http://semver.org/) guidelines as much as possible. 9 | 10 | Releases will be numbered with the following format: 11 | 12 | - `..` 13 | - `..` 14 | 15 | And constructed with the following guidelines: 16 | 17 | - Breaking backward compatibility bumps the major and resets the minor and patch. 18 | - New additions without breaking backward compatibility bump the minor and reset the patch. 19 | - Bug fixes and misc changes bump the patch. 20 | 21 | 22 | ## Pull Requests 23 | 24 | The pull request process differs for new features and bugs. 25 | 26 | Pull requests for bugs may be sent without creating any proposal issue. If you believe that you know of a solution for a bug that has been filed, please leave a comment detailing your proposed fix or create a pull request with the fix mentioning that issue id. 27 | 28 | 29 | ## Coding Standards 30 | 31 | This project follows the FIG PHP Standards Recommendations compliant with the [PSR-1: Basic Coding Standard](http://www.php-fig.org/psr/psr-1/), [PSR-2: Coding Style Guide](http://www.php-fig.org/psr/psr-2/) and [PSR-4: Autoloader](http://www.php-fig.org/psr/psr-4/) to ensure a high level of interoperability between shared PHP code. If you notice any compliance oversights, please send a patch via pull request. 32 | 33 | 34 | ## Feature Requests 35 | 36 | If you have a proposal or a feature request, you may create an issue with `[Proposal]` in the title. 37 | 38 | The proposal should also describe the new feature, as well as implementation ideas. The proposal will then be reviewed and either approved or denied. Once a proposal is approved, a pull request may be created implementing the new feature. 39 | 40 | 41 | ## Git Flow 42 | 43 | This project follows [Git-Flow](http://nvie.com/posts/a-successful-git-branching-model/), and as such has `master` (latest stable releases), `develop` (latest WIP development) and X.Y support branches (when there's multiple major versions). 44 | 45 | Accordingly all pull requests MUST be sent to the `develop` branch. 46 | 47 | > **Note:** Pull requests which do not follow these guidelines will be closed without any further notice. 48 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016-2021, Rinvex LLC, 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rinvex Cacheable 2 | 3 | ⚠️ This package is abandoned and no longer maintained. No replacement package was suggested. ⚠️ 4 | 5 | 👉 If you are interested to step on as the main maintainer of this package, please [reach out to me](https://twitter.com/omranic)! 6 | 7 | --- 8 | 9 | **Rinvex Cacheable** is a granular, intuitive, and fluent caching system for eloquent models. Simple, but yet powerful, plug-n-play with no hassle. 10 | 11 | [![Packagist](https://img.shields.io/packagist/v/rinvex/laravel-cacheable.svg?label=Packagist&style=flat-square)](https://packagist.org/packages/rinvex/laravel-cacheable) 12 | [![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/rinvex/laravel-cacheable.svg?label=Scrutinizer&style=flat-square)](https://scrutinizer-ci.com/g/rinvex/laravel-cacheable/) 13 | [![Travis](https://img.shields.io/travis/rinvex/laravel-cacheable.svg?label=TravisCI&style=flat-square)](https://travis-ci.org/rinvex/laravel-cacheable) 14 | [![StyleCI](https://styleci.io/repos/79321486/shield)](https://styleci.io/repos/79321486) 15 | [![License](https://img.shields.io/packagist/l/rinvex/laravel-cacheable.svg?label=License&style=flat-square)](https://github.com/rinvex/laravel-cacheable/blob/develop/LICENSE) 16 | 17 | What this package do -technically- caching eloquent query passing through the `get` method, whatever it is and it's smart enough to indicated any conditions, limit, offset, wheres, orders, groups, ..etc and take that criteria into account when caching and checking for cached version. Also by default any create, update, or delete event will flush all cache for that specific model. It uses default Laravel caching system, and utilizes whatever cache driver you are using. Awesome, right? 18 | 19 | 20 | ## Installation & Usage 21 | 22 | 1. Install the package via composer: 23 | ```shell 24 | composer require rinvex/laravel-cacheable 25 | ``` 26 | 27 | 2. Use the `\Rinvex\Cacheable\CacheableEloquent` in your desired model, and you're done! 28 | 29 | 3. Seriously, that's it! 30 | 31 | Check the [`CacheableEloquent`](src/CacheableEloquent.php) source code for more awesome stuff if you need advanced control. 32 | 33 | 34 | ## Optional Features 35 | 36 | You can optionally override model caching behaviour per model as follows: 37 | 38 | ```php 39 | /** 40 | * Indicate if the model cache clear is enabled. 41 | * 42 | * @var bool 43 | */ 44 | protected $cacheClearEnabled = true; 45 | 46 | /** 47 | * The model cache driver. 48 | * 49 | * @var string 50 | */ 51 | protected $cacheDriver = 'memcached'; 52 | 53 | /** 54 | * The model cache lifetime. 55 | * 56 | * @var int 57 | */ 58 | protected $cacheLifetime = -1; 59 | ``` 60 | 61 | 62 | ## Changelog 63 | 64 | Refer to the [Changelog](CHANGELOG.md) for a full history of the project. 65 | 66 | 67 | ## Support 68 | 69 | The following support channels are available at your fingertips: 70 | 71 | - [Chat on Slack](https://bit.ly/rinvex-slack) 72 | - [Help on Email](mailto:help@rinvex.com) 73 | - [Follow on Twitter](https://twitter.com/rinvex) 74 | 75 | 76 | ## Contributing & Protocols 77 | 78 | Thank you for considering contributing to this project! The contribution guide can be found in [CONTRIBUTING.md](CONTRIBUTING.md). 79 | 80 | Bug reports, feature requests, and pull requests are very welcome. 81 | 82 | - [Versioning](CONTRIBUTING.md#versioning) 83 | - [Pull Requests](CONTRIBUTING.md#pull-requests) 84 | - [Coding Standards](CONTRIBUTING.md#coding-standards) 85 | - [Feature Requests](CONTRIBUTING.md#feature-requests) 86 | - [Git Flow](CONTRIBUTING.md#git-flow) 87 | 88 | 89 | ## Security Vulnerabilities 90 | 91 | If you discover a security vulnerability within this project, please send an e-mail to [help@rinvex.com](help@rinvex.com). All security vulnerabilities will be promptly addressed. 92 | 93 | 94 | ## About Rinvex 95 | 96 | Rinvex is a software solutions startup, specialized in integrated enterprise solutions for SMEs established in Alexandria, Egypt since June 2016. We believe that our drive The Value, The Reach, and The Impact is what differentiates us and unleash the endless possibilities of our philosophy through the power of software. We like to call it Innovation At The Speed Of Life. That’s how we do our share of advancing humanity. 97 | 98 | 99 | ## License 100 | 101 | This software is released under [The MIT License (MIT)](LICENSE). 102 | 103 | (c) 2016-2021 Rinvex LLC, Some rights reserved. 104 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rinvex/laravel-cacheable", 3 | "description": "Rinvex Cacheable is a granular, intuitive, and fluent caching system for eloquent models. Simple, but yet powerful, plug-n-play with no hassle.", 4 | "type": "library", 5 | "keywords": [ 6 | "trait", 7 | "model", 8 | "laravel", 9 | "eloquent", 10 | "intuitive", 11 | "cacheable", 12 | "granular", 13 | "rinvex", 14 | "fluent", 15 | "query", 16 | "cache" 17 | ], 18 | "license": "MIT", 19 | "homepage": "https://rinvex.com", 20 | "support": { 21 | "email": "help@rinvex.com", 22 | "issues": "https://github.com/rinvex/laravel-cacheable/issues", 23 | "source": "https://github.com/rinvex/laravel-cacheable", 24 | "docs": "https://github.com/rinvex/laravel-cacheable/blob/master/README.md" 25 | }, 26 | "authors": [ 27 | { 28 | "name": "Rinvex LLC", 29 | "homepage": "https://rinvex.com", 30 | "email": "help@rinvex.com" 31 | }, 32 | { 33 | "name": "Abdelrahman Omran", 34 | "homepage": "https://omranic.com", 35 | "email": "me@omranic.com", 36 | "role": "Project Lead" 37 | }, 38 | { 39 | "name": "The Generous Laravel Community", 40 | "homepage": "https://github.com/rinvex/laravel-cacheable/contributors" 41 | } 42 | ], 43 | "require": { 44 | "php": "^7.4.0 || ^8.0.0", 45 | "illuminate/cache": "^8.0.0 || ^9.0.0", 46 | "illuminate/contracts": "^8.0.0 || ^9.0.0", 47 | "illuminate/database": "^8.0.0 || ^9.0.0" 48 | }, 49 | "require-dev": { 50 | "codedungeon/phpunit-result-printer": "^0.30.0", 51 | "illuminate/container": "^8.0.0 || ^9.0.0", 52 | "phpunit/phpunit": "^9.5.0" 53 | }, 54 | "autoload": { 55 | "psr-4": { 56 | "Rinvex\\Cacheable\\": "src/" 57 | } 58 | }, 59 | "autoload-dev": { 60 | "psr-4": { 61 | "Rinvex\\Cacheable\\Tests\\": "tests" 62 | } 63 | }, 64 | "scripts": { 65 | "test": "vendor/bin/phpunit" 66 | }, 67 | "config": { 68 | "sort-packages": true, 69 | "preferred-install": "dist", 70 | "optimize-autoloader": true 71 | }, 72 | "minimum-stability": "dev", 73 | "prefer-stable": true 74 | } 75 | -------------------------------------------------------------------------------- /phpstan.neon.dist: -------------------------------------------------------------------------------- 1 | includes: 2 | - ./vendor/nunomaduro/larastan/extension.neon 3 | parameters: 4 | level: 5 5 | paths: 6 | - src 7 | -------------------------------------------------------------------------------- /src/CacheableEloquent.php: -------------------------------------------------------------------------------- 1 | isCacheClearEnabled() || $cachedModel::forgetCache(); 49 | }); 50 | 51 | static::created(function (Model $cachedModel) { 52 | ! $cachedModel->isCacheClearEnabled() || $cachedModel::forgetCache(); 53 | }); 54 | 55 | static::deleted(function (Model $cachedModel) { 56 | ! $cachedModel->isCacheClearEnabled() || $cachedModel::forgetCache(); 57 | }); 58 | } 59 | 60 | /** 61 | * Store the given cache key for the given model by mimicking cache tags. 62 | * 63 | * @param string $modelName 64 | * @param string $cacheKey 65 | * 66 | * @return void 67 | */ 68 | protected static function storeCacheKey(string $modelName, string $cacheKey): void 69 | { 70 | $keysFile = storage_path('framework/cache/data/rinvex.cacheable.json'); 71 | $cacheKeys = static::getCacheKeys($keysFile); 72 | 73 | if (! isset($cacheKeys[$modelName]) || ! in_array($cacheKey, $cacheKeys[$modelName])) { 74 | $cacheKeys[$modelName][] = $cacheKey; 75 | file_put_contents($keysFile, json_encode($cacheKeys)); 76 | } 77 | } 78 | 79 | /** 80 | * Get cache keys from the given file. 81 | * 82 | * @param string $file 83 | * 84 | * @return array 85 | */ 86 | protected static function getCacheKeys($file): array 87 | { 88 | if (! file_exists($file)) { 89 | $dir = dirname($file); 90 | is_dir($dir) || mkdir($dir); 91 | file_put_contents($file, null); 92 | } 93 | 94 | return json_decode(file_get_contents($file), true) ?: []; 95 | } 96 | 97 | /** 98 | * Flush cache keys of the given model by mimicking cache tags. 99 | * 100 | * @param string $modelName 101 | * 102 | * @return array 103 | */ 104 | protected static function flushCacheKeys(string $modelName): array 105 | { 106 | $flushedKeys = []; 107 | $keysFile = storage_path('framework/cache/data/rinvex.cacheable.json'); 108 | $cacheKeys = static::getCacheKeys($keysFile); 109 | 110 | if (isset($cacheKeys[$modelName])) { 111 | $flushedKeys = $cacheKeys[$modelName]; 112 | 113 | unset($cacheKeys[$modelName]); 114 | 115 | file_put_contents($keysFile, json_encode($cacheKeys)); 116 | } 117 | 118 | return $flushedKeys; 119 | } 120 | 121 | /** 122 | * Set the model cache lifetime. 123 | * 124 | * @param int $cacheLifetime 125 | * 126 | * @return $this 127 | */ 128 | public function setCacheLifetime(int $cacheLifetime) 129 | { 130 | $this->cacheLifetime = $cacheLifetime; 131 | 132 | return $this; 133 | } 134 | 135 | /** 136 | * Get the model cache lifetime. 137 | * 138 | * @return int 139 | */ 140 | public function getCacheLifetime(): int 141 | { 142 | return $this->cacheLifetime ?? -1; 143 | } 144 | 145 | /** 146 | * Set the model cache driver. 147 | * 148 | * @param string $cacheDriver 149 | * 150 | * @return $this 151 | */ 152 | public function setCacheDriver($cacheDriver) 153 | { 154 | $this->cacheDriver = $cacheDriver; 155 | 156 | return $this; 157 | } 158 | 159 | /** 160 | * Get the model cache driver. 161 | * 162 | * @return string|null 163 | */ 164 | public function getCacheDriver(): ?string 165 | { 166 | return $this->cacheDriver ?? null; 167 | } 168 | 169 | /** 170 | * Determine if model cache clear is enabled. 171 | * 172 | * @return bool 173 | */ 174 | public function isCacheClearEnabled(): bool 175 | { 176 | return $this->cacheClearEnabled ?? true; 177 | } 178 | 179 | /** 180 | * Forget the model cache. 181 | * 182 | * @return void 183 | */ 184 | public static function forgetCache() 185 | { 186 | static::fireCacheFlushEvent('cache.flushing'); 187 | 188 | // Flush cache tags 189 | if (method_exists(app('cache')->getStore(), 'tags')) { 190 | app('cache')->tags(static::class)->flush(); 191 | } else { 192 | // Flush cache keys, then forget actual cache 193 | foreach (static::flushCacheKeys(static::class) as $cacheKey) { 194 | app('cache')->forget($cacheKey); 195 | } 196 | } 197 | 198 | static::fireCacheFlushEvent('cache.flushed', false); 199 | } 200 | 201 | /** 202 | * Fire the given event for the model. 203 | * 204 | * @param string $event 205 | * @param bool $halt 206 | * 207 | * @return mixed 208 | */ 209 | protected static function fireCacheFlushEvent($event, $halt = true) 210 | { 211 | if (! isset(static::$dispatcher)) { 212 | return true; 213 | } 214 | 215 | // We will append the names of the class to the event to distinguish it from 216 | // other model events that are fired, allowing us to listen on each model 217 | // event set individually instead of catching event for all the models. 218 | $event = "eloquent.{$event}: ".static::class; 219 | 220 | $method = $halt ? 'until' : 'dispatch'; 221 | 222 | return static::$dispatcher->{$method}($event, static::class); 223 | } 224 | 225 | /** 226 | * Reset cached model to its defaults. 227 | * 228 | * @return $this 229 | */ 230 | public function resetCacheConfig() 231 | { 232 | ! $this->cacheDriver || $this->cacheDriver = null; 233 | ! $this->cacheLifetime || $this->cacheLifetime = -1; 234 | 235 | return $this; 236 | } 237 | 238 | /** 239 | * Generate unique cache key. 240 | * 241 | * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder 242 | * @param array $columns 243 | * 244 | * @return string 245 | */ 246 | protected function generateCacheKey($builder, array $columns): string 247 | { 248 | $query = $builder instanceof Builder ? $builder->getQuery() : $builder; 249 | $vars = [ 250 | 'aggregate' => $query->aggregate, 251 | 'columns' => $query->columns, 252 | 'distinct' => $query->distinct, 253 | 'from' => $query->from, 254 | 'joins' => $query->joins, 255 | 'wheres' => $query->wheres, 256 | 'groups' => $query->groups, 257 | 'havings' => $query->havings, 258 | 'orders' => $query->orders, 259 | 'limit' => $query->limit, 260 | 'offset' => $query->offset, 261 | 'unions' => $query->unions, 262 | 'unionLimit' => $query->unionLimit, 263 | 'unionOffset' => $query->unionOffset, 264 | 'unionOrders' => $query->unionOrders, 265 | 'lock' => $query->lock, 266 | ]; 267 | 268 | return md5(json_encode([ 269 | $vars, 270 | $columns, 271 | static::class, 272 | $this->getCacheDriver(), 273 | $this->getCacheLifetime(), 274 | $builder instanceof Builder ? $builder->getEagerLoads() : null, 275 | $builder->getBindings(), 276 | $builder->toSql(), 277 | ])); 278 | } 279 | 280 | /** 281 | * Cache given callback. 282 | * 283 | * @param \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $builder 284 | * @param array $columns 285 | * @param \Closure $closure 286 | * 287 | * @return mixed 288 | */ 289 | public function cacheQuery($builder, array $columns, Closure $closure) 290 | { 291 | $modelName = $this->getMorphClass(); 292 | $lifetime = $this->getCacheLifetime(); 293 | $cacheKey = $this->generateCacheKey($builder, $columns); 294 | 295 | // Switch cache driver on runtime 296 | if ($driver = $this->getCacheDriver()) { 297 | app('cache')->setDefaultDriver($driver); 298 | } 299 | 300 | // We need cache tags, check if default driver supports it 301 | if (method_exists(app('cache')->getStore(), 'tags')) { 302 | $result = $lifetime === -1 ? app('cache')->tags($modelName)->rememberForever($cacheKey, $closure) : app('cache')->tags($modelName)->remember($cacheKey, $lifetime, $closure); 303 | 304 | return $result; 305 | } 306 | 307 | $result = $lifetime === -1 ? app('cache')->rememberForever($cacheKey, $closure) : app('cache')->remember($cacheKey, $lifetime, $closure); 308 | 309 | // Default cache driver doesn't support tags, let's do it manually 310 | static::storeCacheKey($modelName, $cacheKey); 311 | 312 | // We're done, let's clean up! 313 | $this->resetCacheConfig(); 314 | 315 | return $result; 316 | } 317 | 318 | /** 319 | * Create a new Eloquent query builder for the model. 320 | * 321 | * @param \Illuminate\Database\Query\Builder $query 322 | * 323 | * @return \Illuminate\Database\Eloquent\Builder|static 324 | */ 325 | public function newEloquentBuilder($query) 326 | { 327 | return new EloquentBuilder($query); 328 | } 329 | } 330 | -------------------------------------------------------------------------------- /src/EloquentBuilder.php: -------------------------------------------------------------------------------- 1 | applyScopes(); 25 | 26 | $closure = function () use ($builder, $columns) { 27 | // If we actually found models we will also eager load any relationships that 28 | // have been specified as needing to be eager loaded, which will solve the 29 | // n+1 query issue for the developers to avoid running a lot of queries. 30 | if (count($models = $builder->getModels($columns)) > 0) { 31 | $models = $builder->eagerLoadRelations($models); 32 | } 33 | 34 | return $builder->model->newCollection($models); 35 | }; 36 | 37 | // Check if cache is enabled 38 | if ($builder->model->getCacheLifetime()) { 39 | return $builder->model->cacheQuery($builder, $columns, $closure); 40 | } 41 | 42 | // Cache disabled, just execute query & return result 43 | $results = call_user_func($closure); 44 | 45 | // We're done, let's clean up! 46 | $builder->model->resetCacheConfig(); 47 | 48 | return $results; 49 | } 50 | 51 | /** 52 | * Get an array with the values of a given column. 53 | * 54 | * @param string $column 55 | * @param string|null $key 56 | * 57 | * @return \Illuminate\Support\Collection 58 | */ 59 | public function pluck($column, $key = null): Collection 60 | { 61 | $builder = $this->toBase(); 62 | 63 | $closure = function () use ($builder, $column, $key) { 64 | $results = $builder->pluck($column, $key); 65 | 66 | // If the model has a mutator for the requested column, we will spin through 67 | // the results and mutate the values so that the mutated version of these 68 | // columns are returned as you would expect from these Eloquent models. 69 | if (! $this->model->hasGetMutator($column) && 70 | ! $this->model->hasCast($column) && 71 | ! in_array($column, $this->model->getDates())) { 72 | return $results; 73 | } 74 | 75 | return $results->map(function ($value) use ($column) { 76 | return $this->model->newFromBuilder([$column => $value])->{$column}; 77 | }); 78 | }; 79 | 80 | // Check if cache is enabled 81 | if ($this->model->getCacheLifetime()) { 82 | return $this->model->cacheQuery($builder, (array) $column, $closure); 83 | } 84 | 85 | // Cache disabled, just execute query & return result 86 | $results = call_user_func($closure); 87 | 88 | // We're done, let's clean up! 89 | $this->model->resetCacheConfig(); 90 | 91 | return $results; 92 | } 93 | } 94 | --------------------------------------------------------------------------------