mirror of
https://github.com/nextcloud/documentation.git
synced 2026-01-02 09:49:33 +07:00
feat(devmanual): In-memory cache factory
Signed-off-by: Christoph Wurst <christoph@winzerhof-wurst.at>
This commit is contained in:
@@ -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<testing-php>`:
|
||||
|
||||
.. code-block:: php
|
||||
:caption: lib/Service/PictureService.php
|
||||
:emphasize-lines: 15-19
|
||||
|
||||
<?php
|
||||
|
||||
namespace OCA\MyApp\Service;
|
||||
|
||||
use OCP\ICacheFactory;
|
||||
|
||||
class PictureService {
|
||||
private ICacheFactory $cacheFactory;
|
||||
|
||||
public function __construct(ICacheFactory $cacheFactory){
|
||||
$this->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
|
||||
-----------
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ Testing
|
||||
|
||||
All PHP classes can be tested with `PHPUnit <https://phpunit.de/>`_, JavaScript can be tested by using `Karma <http://karma-runner.github.io>`_.
|
||||
|
||||
|
||||
.. _testing-php:
|
||||
|
||||
PHP
|
||||
---
|
||||
|
||||
Reference in New Issue
Block a user