Skip to content

Commit

Permalink
Configuration option to disable events on cache
Browse files Browse the repository at this point in the history
Allow caches to be defined without auto-registering events dispatcher.

On in-memory caches like array or apc, the overhead of triggering events results an 80%+ overhead in basic cache operations.  This change allows a a config value on any cache definition to disable events for that particular Repository.
  • Loading branch information
serpentblade committed Apr 12, 2024
1 parent dec31b0 commit 2d89e57
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/Illuminate/Cache/CacheManager.php
Expand Up @@ -288,8 +288,10 @@ protected function newDynamodbClient(array $config)
*/
public function repository(Store $store, array $config = [])
{
return tap(new Repository($store, Arr::only($config, ['store'])), function ($repository) {
$this->setEventDispatcher($repository);
return tap(new Repository($store, Arr::only($config, ['store'])), function ($repository) use ($config) {
if ($config['with_events'] ?? true) {
$this->setEventDispatcher($repository);
}
});
}

Expand Down
30 changes: 30 additions & 0 deletions tests/Cache/CacheManagerTest.php
Expand Up @@ -277,6 +277,36 @@ public function testThrowExceptionWhenUnknownStoreIsUsed()
$cacheManager->store('alien_store');
}

public function testMakesRepositoryWithoutDispatcherWhenEventsDisabled()
{
$userConfig = [
'cache' => [
'stores' => [
'my_store' => [
'driver' => 'array',
],
'my_store_without_events' => [
'driver' => 'array',
'with_events' => false,
]
],
],
];

$app = $this->getApp($userConfig);
$app->bind(Dispatcher::class, fn () => new Event);

$cacheManager = new CacheManager($app);

// The repository will have an event dispatcher
$repo = $cacheManager->store('my_store');
$this->assertNotNull($repo->getEventDispatcher());

// This repository will not have an event dispatcher as 'with_events' is false
$repoWithoutEvents = $cacheManager->store('my_store_without_events');
$this->assertNull($repoWithoutEvents->getEventDispatcher());
}

protected function getApp(array $userConfig)
{
$app = new Container;
Expand Down

0 comments on commit 2d89e57

Please sign in to comment.