├── config └── config.php ├── .github ├── FUNDING.yml ├── dependabot.yml └── workflows │ └── php.yml ├── LICENSE.md ├── phpunit.xml ├── src ├── RememberableQueryServiceProvider.php └── RememberableQuery.php ├── composer.json └── README.md /config/config.php: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | tests 15 | 16 | 17 | 18 | 19 | src/ 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/RememberableQueryServiceProvider.php: -------------------------------------------------------------------------------- 1 | cacheKey = $cacheKey ?? $this->cacheKeyHash(); 52 | $this->cache = $cache->store($store); 53 | } 54 | 55 | /** 56 | * Returns the auto-generated cache key 57 | * 58 | * @return string 59 | */ 60 | public function cacheKeyHash(): string 61 | { 62 | return 'query|'.base64_encode( 63 | md5($this->builder->toSql().implode('', $this->builder->getBindings()), true) 64 | ); 65 | } 66 | 67 | /** 68 | * Dynamically call the query builder until a result is expected 69 | * 70 | * @param string $method 71 | * @param array $arguments 72 | * 73 | * @return mixed 74 | */ 75 | public function __call(string $method, array $arguments): mixed 76 | { 77 | return $this->cache->remember($this->cacheKey, $this->ttl, function () use ($method, $arguments) { 78 | return $this->wait 79 | ? $this->getLockResult($method, $arguments) 80 | : $this->getResult($method, $arguments); 81 | }); 82 | } 83 | 84 | /** 85 | * Returns the results from a lock callback. 86 | * 87 | * @param string $method 88 | * @param array $arguments 89 | * 90 | * @return mixed 91 | */ 92 | protected function getLockResult(string $method, array $arguments): mixed 93 | { 94 | return $this->cache 95 | ->lock($this->cacheKey, $this->wait) 96 | ->block($this->wait, fn() => $this->getResult($method, $arguments)); 97 | } 98 | 99 | /** 100 | * Forwards the call to the builder and retrieves the result. 101 | * 102 | * @param string $method 103 | * @param array $arguments 104 | * 105 | * @return mixed 106 | */ 107 | protected function getResult(string $method, array $arguments): mixed 108 | { 109 | $result = $this->forwardCallTo($this->builder, $method, $arguments); 110 | 111 | // Force the developer to use this as before-last method in the query builder. 112 | if ($result instanceof Builder || $result instanceof EloquentBuilder) { 113 | throw new RuntimeException("The `remember()` method call is not before query execution: [$method] called."); 114 | } 115 | 116 | return $result; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Package superseeded by [Laragear/CacheQuery](https://github.com/Laragear/CacheQuery) 2 | 3 | --- 4 | 5 | # Rememberable Queries 6 | 7 | Remember your Query results using only one method. Yes, only one. 8 | 9 | ```php 10 | Articles::latest('published_at')->take(10)->remember()->get(); 11 | ``` 12 | 13 | ## Requirements 14 | 15 | * PHP 8.0 16 | * Laravel 8.x 17 | 18 | ## Installation 19 | 20 | You can install the package via composer: 21 | 22 | ```bash 23 | composer require darkghosthunter/rememberable-query 24 | ``` 25 | 26 | ## Usage 27 | 28 | Just use the `remember()` method to remember a Query result **before the execution**. That's it. The method automatically remembers the result for 60 seconds. 29 | 30 | ```php 31 | use Illuminate\Support\Facades\DB; 32 | use App\Models\Article; 33 | 34 | $database = DB::table('articles')->latest('published_at')->take(10)->remember()->get(); 35 | 36 | $eloquent = Article::latest('published_at')->take(10)->remember()->get(); 37 | ``` 38 | 39 | The next time you call the **same** query, the result will be retrieved from the cache instead of running the SQL statement in the database, even if the result is `null` or `false`. 40 | 41 | > The `remember()` will throw an error if you build a query instead of executing it. 42 | 43 | ### Time-to-live 44 | 45 | By default, queries are remembered by 60 seconds, but you're free to use any length, `Datetime`, `DateInterval` or Carbon instance. 46 | 47 | ```php 48 | DB::table('articles')->latest('published_at')->take(10)->remember(60 * 60)->get(); 49 | 50 | Article::latest('published_at')->take(10)->remember(now()->addHour())->get(); 51 | ``` 52 | 53 | ### Custom Cache Key 54 | 55 | The auto-generated cache key is an BASE64-MD5 hash of the SQL query and its bindings, which avoids any collision with other queries while keeping the cache key short. 56 | 57 | You can use any string as you want, but is recommended to append `query|` to avoid conflicts with other cache keys in your application. 58 | 59 | ```php 60 | Article::latest('published_at')->take(10)->remember(30, 'query|latest_articles')->get(); 61 | ``` 62 | 63 | Alternatively, you can use an [custom Cache Store](#custom-cache-store) for remembering queries. 64 | 65 | ### Custom Cache Store 66 | 67 | In some scenarios, using the default cache of your application may be detrimental compared to the database performance, or may conflict with other keys. You can use any other Cache Store by setting a third parameter, or a named parameter. 68 | 69 | ```php 70 | Article::latest('published_at')->take(10)->remember(store: 'redis')->get(); 71 | ``` 72 | 73 | ### Cache Lock (data races) 74 | 75 | On multiple processes, the Query may be executed multiple times until the first process is able to store the result in the cache, specially when these take more than 1 second. To avoid this, set the `wait` parameter with the number of seconds to hold the lock acquired. 76 | 77 | ```php 78 | Article::latest('published_at')->take(200)->remember(wait: 5)->get(); 79 | ``` 80 | 81 | The first process will acquire the lock for the given seconds, execute the query and store the result. The next processes will wait until the cache data is available to retrieve the result from there. 82 | 83 | > If you need to use this across multiple processes, use the [cache lock](https://laravel.com/docs/cache#managing-locks-across-processes) directly. 84 | 85 | ### Idempotent queries 86 | 87 | While the reason behind remembering a Query is to cache the data retrieved from a database, you can use this to your advantage to create [idempotent](https://en.wikipedia.org/wiki/Idempotence) queries. 88 | 89 | For example, you can make this query only execute once every day for a given user ID. 90 | 91 | ```php 92 | $key = auth()->user()->getAuthIdentifier(); 93 | 94 | Article::whereKey(54)->remember(now()->addHour(), "query|user:$key")->increment('unique_views'); 95 | ``` 96 | 97 | Subsequent executions of this query won't be executed at all until the cache expires, so in the above example we have surprisingly created a "unique views" mechanic. 98 | 99 | ## Operations are **NOT** commutative 100 | 101 | Altering the Builder methods order will change the auto-generated cache key hash. Even if they are _visually_ the same, the order of statements makes the hash completely different. 102 | 103 | For example, given two similar queries in different parts of the application, these both will **not** share the same cached result: 104 | 105 | ```php 106 | User::whereName('Joe')->whereAge(20)->remember()->first(); 107 | // Cache key: "query|/XreUO1yaZ4BzH2W6LtBSA==" 108 | 109 | User::whereAge(20)->whereName('Joe')->remember()->first(); 110 | // Cache key: "query|muDJevbVppCsTFcdeZBxsA==" 111 | ``` 112 | 113 | To ensure you're hitting the same cache on similar queries, use a [custom cache key](#custom-cache-key). With this, all queries using the same key will share the same cached result: 114 | 115 | ```php 116 | User::whereName('Joe')->whereAge(20)->remember(60, 'query|find_joe')->first(); 117 | User::whereAge(20)->whereName('Joe')->remember(60, 'query|find_joe')->first(); 118 | ``` 119 | 120 | This will allow you to even retrieve the data outside the query, by just asking directly to the cache. 121 | 122 | ```php 123 | $joe = Cache::get('query|find_joe'); 124 | ``` 125 | 126 | ## License 127 | 128 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 129 | --------------------------------------------------------------------------------