From 2fe467210fab389f1578dae4444569cffaa3e5ef Mon Sep 17 00:00:00 2001 From: Christoph Wurst Date: Fri, 13 Oct 2023 13:50:19 +0200 Subject: [PATCH] feat(devmanual): In-memory cache factory Signed-off-by: Christoph Wurst --- developer_manual/basics/caching.rst | 38 +++++++++++++++++++++++++++++ developer_manual/basics/testing.rst | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/developer_manual/basics/caching.rst b/developer_manual/basics/caching.rst index 557a8d232..21da6c0a2 100644 --- a/developer_manual/basics/caching.rst +++ b/developer_manual/basics/caching.rst @@ -59,6 +59,44 @@ The ``OCP\Cache\CappedMemoryCache`` class is an in-memory cache that can be used } } + +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`: + +.. code-block:: php + :caption: lib/Service/PictureService.php + :emphasize-lines: 15-19 + + cacheFactory = $cacheFactory; + } + + public function getPicture(string $url): void { + // Initialize the cache. The instance has to be remembered because + // each call to `createInMemory` returns a fresh, empty cache. + if ($this->cache === null) { + $this->cache = $this->cacheFactory->createInMemory(64); + } + + if (isset($this->cache[$url])) { + return $this->cache[$url]; + } + + // Fetch picture and serialize result into $picture + + $this->cache[$url] = $picture; + return $picture; + } + } + Local cache ----------- diff --git a/developer_manual/basics/testing.rst b/developer_manual/basics/testing.rst index 21eb78aa8..3d56d5794 100644 --- a/developer_manual/basics/testing.rst +++ b/developer_manual/basics/testing.rst @@ -6,7 +6,7 @@ Testing All PHP classes can be tested with `PHPUnit `_, JavaScript can be tested by using `Karma `_. - +.. _testing-php: PHP ---