Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add factory method for in-memory caches #40868

Merged
merged 1 commit into from Oct 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/private/Memcache/Factory.php
Expand Up @@ -31,6 +31,7 @@
*/
namespace OC\Memcache;

use OCP\Cache\CappedMemoryCache;
use OCP\Profiler\IProfiler;
use OCP\ICache;
use OCP\ICacheFactory;
Expand Down Expand Up @@ -184,6 +185,10 @@ public function isAvailable(): bool {
return $this->distributedCacheClass !== self::NULL_CACHE;
}

public function createInMemory(int $capacity = 512): ICache {
return new CappedMemoryCache($capacity);
}

/**
* Check if a local memory cache backend is available
*
Expand Down
16 changes: 16 additions & 0 deletions lib/public/ICacheFactory.php
Expand Up @@ -75,4 +75,20 @@ public function createDistributed(string $prefix = ''): ICache;
* @since 13.0.0
*/
public function createLocal(string $prefix = ''): ICache;

/**
* Create an in-memory cache instance
*
* Useful for remembering values inside one process. Cache memory is cleared
* when the object is garbage-collected. Implementation may also expire keys
* earlier when the TTL is reached or too much memory is consumed.
*
* Cache keys are local to the cache object. When building two in-memory
* caches, there is no data exchange between the instances.
*
* @param int $capacity maximum number of cache keys
* @return ICache
* @since 28.0.0
*/
public function createInMemory(int $capacity = 512): ICache;
}
11 changes: 11 additions & 0 deletions tests/lib/Memcache/FactoryTest.php
Expand Up @@ -140,4 +140,15 @@ public function testCacheNotAvailableException($localCache, $distributedCache) {
$profiler = $this->getMockBuilder(IProfiler::class)->getMock();
new \OC\Memcache\Factory('abc', $logger, $profiler, $localCache, $distributedCache);
}

public function testCreateInMemory(): void {
$logger = $this->getMockBuilder(LoggerInterface::class)->getMock();
$profiler = $this->getMockBuilder(IProfiler::class)->getMock();
$factory = new \OC\Memcache\Factory('abc', $logger, $profiler, null, null, null);

$cache = $factory->createInMemory();
$cache->set('test', 48);

self::assertSame(48, $cache->get('test'));
}
}