Skip to content

Commit 64d6dc0

Browse files
PHPORM-174 Add doc for cache and locks (#2909)
Co-authored-by: Jordan Smith <[email protected]>
1 parent f95eb66 commit 64d6dc0

File tree

3 files changed

+260
-0
lines changed

3 files changed

+260
-0
lines changed

Diff for: docs/cache.txt

+244
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
.. _laravel-cache:
2+
3+
===============
4+
Cache and Locks
5+
===============
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: php framework, cache, lock, code example
13+
14+
Configuration
15+
-------------
16+
17+
To use MongoDB as a backend for `Laravel Cache and Locks <https://laravel.com/docs/{+laravel-docs-version+}/cache>`__,
18+
add a store configuration by specifying the ``mongodb`` driver in ``config/cache.php``:
19+
20+
.. code-block:: php
21+
22+
'stores' => [
23+
'mongodb' => [
24+
'driver' => 'mongodb',
25+
'connection' => 'mongodb',
26+
'collection' => 'cache',
27+
'lock_connection' => 'mongodb',
28+
'lock_collection' => 'cache_locks',
29+
'lock_lottery' => [2, 100],
30+
'lock_timeout' => 86400,
31+
],
32+
],
33+
34+
To configure the ``mongodb`` database connection, see the :ref:`laravel-fundamentals-connection` section.
35+
36+
The following table describes a list of cache and lock options
37+
and their default values:
38+
39+
.. list-table::
40+
:header-rows: 1
41+
:widths: 25 75
42+
43+
* - Setting
44+
- Description
45+
46+
* - ``driver``
47+
- **Required**. Specifies the lock driver to use. Must be ``mongodb``.
48+
49+
* - ``connection``
50+
- **Required**. The database connection used to store cache items. It must be a ``mongodb`` connection.
51+
52+
* - ``collection``
53+
- Default ``cache``. Name of the MongoDB collection to store cache items.
54+
55+
* - ``lock_connection``
56+
- Default to the cache ``connection``. The database connection used to store locks. It must be a ``mongodb`` connection.
57+
58+
* - ``lock_collection``
59+
- Default ``cache_locks``. Name of the MongoDB collection to store locks.
60+
61+
* - ``lock_lottery``
62+
- Default ``[2, 100]``. Probability ``[chance, total]`` of pruning expired cache items. Set to ``[0, 0]`` to disable.
63+
64+
* - ``lock_timeout``
65+
- Default ``86400``. Time-to-live of the locks, in seconds.
66+
67+
68+
Set Up Auto-Expiration Indexes
69+
-------------------------------
70+
71+
The :manual:`TTL indexes </core/index-ttl/>` integrated into MongoDB automatically
72+
delete documents when they expire. Their use is optional with the ``mongodb``
73+
driver, but recommended. The indexes provide better performance by delegating the
74+
deletion of expired documents to MongoDB instead of requiring the application to
75+
perform this task.
76+
77+
Create the indexes with a migration that calls the
78+
``createTTLIndex()`` methods provided by both the cache, and the lock stores:
79+
80+
.. literalinclude:: /includes/cache/migration.php
81+
:language: php
82+
:emphasize-lines: 11,12
83+
:dedent:
84+
85+
Then run the migration:
86+
87+
.. code-block:: none
88+
89+
php artisan migrate
90+
91+
Alternatively, you can create the index by using :mdb-shell:`MongoDB Shell <>` (``mongosh``):
92+
93+
.. code-block:: ts
94+
95+
db.cache.createIndex(
96+
/* Field that holds the expiration date */
97+
{ expires_at: 1 },
98+
/* Delay to remove items after expiration */
99+
{ expireAfterSeconds: 0 }
100+
)
101+
102+
If you use Locks, disable ``lock_lottery`` by setting the probability to ``0``:
103+
104+
.. code-block:: php
105+
:emphasize-lines: 4
106+
107+
'stores' => [
108+
'mongodb' => [
109+
'driver' => 'mongodb',
110+
'connection' => 'mongodb',
111+
'lock_lottery' => [0, 100], // Disabled
112+
],
113+
],
114+
115+
Using MongoDB Cache
116+
-------------------
117+
118+
The Laravel cache can be used to store any serializable data using the facade
119+
``Illuminate\Support\Facades\Cache``.
120+
121+
This example performs the following actions:
122+
123+
- Gets the cache repository with the ``mongodb`` store
124+
- Tries to read and return the cache item named ``foo``
125+
- If missing, calls the closure to compute the value, stores the value forever, and returns it
126+
127+
.. code-block:: php
128+
129+
use Illuminate\Support\Facades\Cache;
130+
131+
$value = Cache::store('mongodb')->get('foo', function () {
132+
return [1, 2, 3];
133+
});
134+
135+
By default, cached objects do not expire. However, it is possible to define an expiry time, as shown in the following example:
136+
137+
.. code-block:: php
138+
139+
Cache::store('mongodb')->set('foo', 'abc', '1 day');
140+
141+
Incrementing and decrementing a value is also supported if the value is
142+
initialized before. The following example initializes the counter to ``3``,
143+
adds 5, and removes 2.
144+
145+
.. code-block:: php
146+
147+
Cache::store('mongodb')->set('counter', 3);
148+
Cache::store('mongodb')->increment('counter', 5);
149+
Cache::store('mongodb')->decrement('counter', 2);
150+
151+
.. note::
152+
153+
{+odm-short+} supports incrementing and decrementing with integer and float values.
154+
155+
For more information about using the cache, see the `Laravel Cache documentation
156+
<https://laravel.com/docs/{+laravel-docs-version+}/cache#cache-usage>`__.
157+
158+
Configuring MongoDB as the Default Cache
159+
----------------------------------------
160+
161+
To use the ``mongodb`` store by default, change the default store in
162+
``config/cache.php``.
163+
164+
.. code-block:: php
165+
:emphasize-lines: 2
166+
167+
return [
168+
'default' => env('CACHE_STORE', 'mongodb'),
169+
'stores' => [
170+
'mongodb' => [
171+
'driver' => 'mongodb',
172+
'connection' => 'mongodb',
173+
],
174+
],
175+
];
176+
177+
.. note::
178+
179+
We have deliberately omitted all optional parameters in the previous example,
180+
so the default values are applied.
181+
182+
The ``CACHE_STORE`` variable can be set in your environment or in
183+
the ``.env`` file. Update or remove it as follows:
184+
185+
.. code-block:: none
186+
187+
CACHE_STORE=mongodb
188+
189+
Then you can use the ``Illuminate\Support\Facades\Cache`` facade and
190+
automatic injection:
191+
192+
.. code-block:: php
193+
194+
use Illuminate\Support\Facades\Cache;
195+
196+
Cache::get('foo', 5);
197+
198+
The following example shows how to use automatic injection of the cache
199+
manager by using the default store. The example creates a controller that
200+
increments a counter each time it is invoked.
201+
202+
203+
.. code-block:: php
204+
:emphasize-lines: 10,15
205+
206+
<?php
207+
208+
namespace App\Http\Controllers;
209+
210+
use App\Contracts\CacheManager;
211+
212+
class CountController extends Controller
213+
{
214+
public function __construct(
215+
private CacheManager $cache,
216+
) {}
217+
218+
public function hit(): int
219+
{
220+
return $this->cache->increment('counter');
221+
}
222+
}
223+
224+
Using MongoDB Lock
225+
------------------
226+
227+
Atomic locks allow for the manipulation of distributed locks without worrying
228+
about race conditions. The following example implements an atomic lock:
229+
230+
.. code-block:: php
231+
:emphasize-lines: 3
232+
233+
use Illuminate\Support\Facades\Cache;
234+
235+
$lock = Cache::store('mongodb')->lock('foo', 10);
236+
237+
if ($lock->get()) {
238+
// Lock acquired for 10 seconds...
239+
240+
$lock->release();
241+
}
242+
243+
For more information on using locks, see the `Laravel Locks documentation
244+
<https://laravel.com/docs/{+laravel-docs-version+}/cache#atomic-locks>`__.

Diff for: docs/includes/cache/migration.php

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
use Illuminate\Database\Migrations\Migration;
4+
use Illuminate\Support\Facades\Cache;
5+
6+
return new class extends Migration
7+
{
8+
public function up(): void
9+
{
10+
$store = Cache::store('mongodb');
11+
$store->createTTLIndex();
12+
$store->lock('')->createTTLIndex();
13+
}
14+
};

Diff for: docs/index.txt

+2
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ Laravel MongoDB
2020
/eloquent-models
2121
/query-builder
2222
/user-authentication
23+
/cache
2324
/queues
2425
/transactions
2526
/issues-and-help
@@ -69,6 +70,7 @@ see the following content:
6970
- :ref:`laravel-query-builder`
7071
- :ref:`laravel-aggregation-builder`
7172
- :ref:`laravel-user-authentication`
73+
- :ref:`laravel-cache`
7274
- :ref:`laravel-queues`
7375
- :ref:`laravel-transactions`
7476

0 commit comments

Comments
 (0)