Skip to content

Commit 03fa3db

Browse files
authored
Merge pull request #11198 from nextcloud/feat/devmanual/in-memory-cache-factory
feat(devmanual): In-memory cache factory
2 parents 3a73067 + 2fe4672 commit 03fa3db

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

developer_manual/basics/caching.rst

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,44 @@ The ``OCP\Cache\CappedMemoryCache`` class is an in-memory cache that can be used
5959
}
6060
}
6161
62+
63+
A cache instance can also be built by the cache factory. This approach allows mocking the injected factory for finer control during :ref:`unit testing<testing-php>`:
64+
65+
.. code-block:: php
66+
:caption: lib/Service/PictureService.php
67+
:emphasize-lines: 15-19
68+
69+
<?php
70+
71+
namespace OCA\MyApp\Service;
72+
73+
use OCP\ICacheFactory;
74+
75+
class PictureService {
76+
private ICacheFactory $cacheFactory;
77+
78+
public function __construct(ICacheFactory $cacheFactory){
79+
$this->cacheFactory = $cacheFactory;
80+
}
81+
82+
public function getPicture(string $url): void {
83+
// Initialize the cache. The instance has to be remembered because
84+
// each call to `createInMemory` returns a fresh, empty cache.
85+
if ($this->cache === null) {
86+
$this->cache = $this->cacheFactory->createInMemory(64);
87+
}
88+
89+
if (isset($this->cache[$url])) {
90+
return $this->cache[$url];
91+
}
92+
93+
// Fetch picture and serialize result into $picture
94+
95+
$this->cache[$url] = $picture;
96+
return $picture;
97+
}
98+
}
99+
62100
Local cache
63101
-----------
64102

developer_manual/basics/testing.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ Testing
66

77
All PHP classes can be tested with `PHPUnit <https://phpunit.de/>`_, JavaScript can be tested by using `Karma <http://karma-runner.github.io>`_.
88

9-
9+
.. _testing-php:
1010

1111
PHP
1212
---

0 commit comments

Comments
 (0)