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 ---