Skip to content

Commit

Permalink
✨ added auto-cleaning of the cache
Browse files Browse the repository at this point in the history
  • Loading branch information
bnomei committed Jul 13, 2024
1 parent da52fae commit c8a402c
Show file tree
Hide file tree
Showing 7 changed files with 73 additions and 9 deletions.
22 changes: 19 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ $value = $cache->get('mykey');

$cache->set('tagging', [
'tags' => ['tag1', 'tag2'],
'value' => 'myvalue',
'other_value' => 'myothervalue',
]);
```

Expand All @@ -245,18 +245,31 @@ filtering my tags or invalidating many cache entries at once.
// NOTE: we are using the cacheCollection() method here
$collection = mongo()->cacheCollection();

// find all that have the tag 'tag1'
// find all that have the tag 'tag1' and are NOT expired
$documents = $collection->find([
'tags' => ['$in' => ['tag1']],
'value.tags' => ['$in' => ['tag1']],
'expires_at' => ['$gt' => time()],
]);
foreach ($documents as $document) {
// $document->value->tags
// $document->value->other_value
}

// delete any cache entry older than 5 minutes
$deleteResult = $collection->deleteMany([
'expires_at' => ['$lt' => time() - 5*60]
]);
$deletedCount = $deleteResult->getDeletedCount();

// you can also manually clean expired cache entries
mongo()->clean();
```

> [!NOTE]
>
> Querying the cache directly is not recommended for regular use-cases. It will not check for the expiration of the
> cache entries and delete them automatically.
## Using the Cache Driver in Kirby

You can also use the MongoDB-based cache as a **cache driver** for Kirby. This will allow you to use it for caching of
Expand Down Expand Up @@ -287,6 +300,9 @@ return [
| username | `null` | |
| password | `null` | |
| database | `kirby` | you can give it any name you want and MongoDB will create it for you |
| uriOptions | `[]` | |
| driverOptions | `[]` | |
| auto-clean-cache | `true` | will clean the cache once before the first get() |
| khulan.read | `false` | read from cache is disabled by default as loading from file might be faster |
| khulan.write | `true` | write to cache for all models that use the ModelWithKhulan trait |
| khulan.patch-files-class | `true` | monkey-patch the \Kirby\CMS\Files class to use Khulan for caching its content |
Expand Down
17 changes: 17 additions & 0 deletions classes/Mongodb.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ final class Mongodb extends Cache
{
protected ?Client $_client = null;

protected bool $hasCleanedOnce = false;

/**
* Sets all parameters which are needed to connect to MongoDB.
*/
Expand All @@ -34,6 +36,7 @@ public function __construct(array $options = [])
'driverOptions' => option('bnomei.mongodb.driverOptions'),
'collection-cache' => option('bnomei.mongodb.collections.cache'),
'collection-content' => option('bnomei.mongodb.collections.content'),
'auto-clean-cache' => option('bnomei.mongodb.auto-clean-cache'),
], $options);

foreach ($this->options as $key => $call) {
Expand Down Expand Up @@ -95,6 +98,11 @@ public function set(string $key, $value, int $minutes = 0): bool
*/
public function retrieve(string $key): ?Value
{
if ($this->options['auto-clean-cache'] && $this->hasCleanedOnce === false) {
$this->clean(time());
$this->hasCleanedOnce = true;
}

$value = $value ?? $this->cacheCollection()->findOne([
'_id' => $this->key($key),
]);
Expand Down Expand Up @@ -183,6 +191,15 @@ public function root(): string
return kirby()->cache('bnomei.mongodb')->root();
}

public function clean(?int $time = null): ?int
{
$result = $this->cacheCollection()->deleteMany([
'expires_at' => ['$lt' => $time ?? time()],
]);

return $result->isAcknowledged() ? $result->getDeletedCount() : null;
}

public function cache(): self
{
return $this;
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "bnomei/kirby-mongodb",
"type": "kirby-plugin",
"version": "1.4.2",
"version": "1.4.3",
"description": "Khulan is a cache driver and content cache with NoSQL interface for Kirby using MongoDB",
"license": "MIT",
"authors": [
Expand Down
2 changes: 1 addition & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions index.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ function khulan(string|array|null $search = null, ?array $options = null): mixed
'password' => null,
'uriOptions' => [],
'driverOptions' => [],
'auto-clean-cache' => true,

// collections
'collections' => [
Expand Down
30 changes: 30 additions & 0 deletions tests/MongodbTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,36 @@
expect($value)->toBe('value');
});

it('can use the cache for array based values', function () {
$mongodb = mongo();
$mongodb->set('tagging', [
'tags' => ['tag1', 'tag2'],
'not_value' => 'notmyvalue',
]);

$collection = mongo()->cacheCollection();
$documents = $collection->find([
'value.tags' => ['$in' => ['tag1']],
]);

foreach ($documents as $document) {
expect($document->value->tags[0])->toEqual('tag1')
->and($document->value->tags[1])->toEqual('tag2')
->and($document->value->not_value)->toEqual('notmyvalue');
}
});

it('can clean expired entries', function () {
$mongodb = mongo();
$mongodb->set('test', 'value', 5);

$mongodb->clean(time() + 5 * 60 + 1);

$value = $mongodb->get('test');

expect($value)->toBeNull();
});

it('will not use the cache in debug mode', function () {
Mongodb::$singleton = null;

Expand Down
8 changes: 4 additions & 4 deletions vendor/composer/installed.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<?php return array(
'root' => array(
'name' => 'bnomei/kirby-mongodb',
'pretty_version' => '1.4.2',
'version' => '1.4.2.0',
'pretty_version' => '1.4.3',
'version' => '1.4.3.0',
'reference' => null,
'type' => 'kirby-plugin',
'install_path' => __DIR__ . '/../../',
Expand All @@ -11,8 +11,8 @@
),
'versions' => array(
'bnomei/kirby-mongodb' => array(
'pretty_version' => '1.4.2',
'version' => '1.4.2.0',
'pretty_version' => '1.4.3',
'version' => '1.4.3.0',
'reference' => null,
'type' => 'kirby-plugin',
'install_path' => __DIR__ . '/../../',
Expand Down

0 comments on commit c8a402c

Please sign in to comment.