From 2d89e579234a33e1b341d3e2fe32b058999fba1e Mon Sep 17 00:00:00 2001 From: Dan Krieger Date: Thu, 11 Apr 2024 17:05:40 -0700 Subject: [PATCH] Configuration option to disable events on cache 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. --- src/Illuminate/Cache/CacheManager.php | 6 ++++-- tests/Cache/CacheManagerTest.php | 30 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Cache/CacheManager.php b/src/Illuminate/Cache/CacheManager.php index f0f0b392e9ae..8e2316aed136 100755 --- a/src/Illuminate/Cache/CacheManager.php +++ b/src/Illuminate/Cache/CacheManager.php @@ -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); + } }); } diff --git a/tests/Cache/CacheManagerTest.php b/tests/Cache/CacheManagerTest.php index b79a8ff82666..37a4f304b83e 100644 --- a/tests/Cache/CacheManagerTest.php +++ b/tests/Cache/CacheManagerTest.php @@ -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;