From a30ad45f95b2f32aa9f1b718bb7f9ebfb1190686 Mon Sep 17 00:00:00 2001 From: Georges Date: Sun, 7 Jan 2024 00:53:46 +0100 Subject: [PATCH 1/6] Prepared migration guide for v10 --- docs/migration/MigratingFromV9ToV10.md | 48 ++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 docs/migration/MigratingFromV9ToV10.md diff --git a/docs/migration/MigratingFromV9ToV10.md b/docs/migration/MigratingFromV9ToV10.md new file mode 100644 index 00000000..206e08b5 --- /dev/null +++ b/docs/migration/MigratingFromV9ToV10.md @@ -0,0 +1,48 @@ +Because the V10 is **relatively** not backward compatible with the V9, here's a guide to help you to migrate your code: + +### :warning: Minimum php version increased to 8.2+ +As of the V9 the mandatory php version has been increased to 8.2+. +Once released, the php versions 8.3, 8.4 will be unit-tested + +### Added Microsoft Azure Cosmos DB driver +Extension Cosmosdb has been added has an extension: `phpfastcache/cosmosdb-extension`. + +### Embedded document-oriented drivers have been moved from the core to their own extensions +- Driver `Arangodb` have been **removed**, use `phpfastcache/arangodb-extension` (via composer) instead. +- Driver `Couchdb` have been **removed**, use `phpfastcache/couchdb-extension` (via composer) instead. +- Driver `Cassandra` have been **removed**, use `phpfastcache/cassandra-extension` (via composer) instead. +- Driver `Dynamodb` have been **removed**, use `phpfastcache/dynamodb-extension` (via composer) instead. +- Driver `Firestore` have been **removed**, use `phpfastcache/firestore-extension` (via composer) instead. +- Driver `Mongodb` have been **removed**, use `phpfastcache/mongodb-extension` (via composer) instead. +- Driver `Solr` have been **removed**, use `phpfastcache/solr-extension` (via composer) instead. + +However, driver `Couchbasev3` has been kept in the core for compatibility reasons but has been deprecated and will be removed as of v11.\ +Use `phpfastcache/couchbasev4-extension` to upgrade your code to the latest version of Couchbase.\ +Common drivers such as `Files`, `Redis`, `Ssdb`, `Sqlite` will stay in the core. + +### `Memstatic` driver renamed to `Memory` +Previously deprecated in v9.2, the driver `Memstatic` has been removed, use `Memory` instead (which is completely identical, only the name changed). + +### `Wincache` driver removed +Previously deprecated in v9.2, the driver has been removed with no replacement due to the lack of updates to PHP 8 [as officially stated by PHP](https://www.php.net/manual/en/install.windows.recommended.php). + +### Class `\Phpfastcache\Config\Config` removed +Use `\Phpfastcache\Config\ConfigurationOption` instead. + +### Class `\Phpfastcache\Helper\CacheConditionalHelper` removed +Use `\Phpfastcache\CacheContract` instead. + +### Configurations deprecations and removals + +#### Global: +Config methods `isPreventCacheSlams()/setPreventCacheSlams()/getCacheSlamsTimeout()/setCacheSlamsTimeout()` from `ConfigurationOption` have moved to `IOConfigurationOption` hence will be reserved to `Files`/`Leveldb`/`Sqlite` drivers. + +#### Firestore: +Config `getCollection()/setCollection()` methods are renamed to `getCollectionName()/setCollectionName()` + +------ +More information in our comprehensive [changelog](./../../CHANGELOG.md). + + + + From 9448a0c119bfd5fb891bab9f41c360d85f6377bc Mon Sep 17 00:00:00 2001 From: Georges Date: Tue, 16 Jan 2024 23:41:52 +0100 Subject: [PATCH 2/6] Rework of events (WIP) --- .github/workflows/testsv2.yml | 2 +- CHANGELOG.md | 197 ++---------------- composer.json | 12 +- .../Cluster/ClusterAggregator.php | 5 +- .../Cluster/ClusterPoolAbstract.php | 10 - .../Drivers/MasterSlaveReplication/Driver.php | 9 +- .../Drivers/RandomReplication/Driver.php | 10 +- lib/Phpfastcache/Config/Config.php | 36 ---- .../Config/ConfigurationOption.php | 61 ------ .../Config/IOConfigurationOption.php | 7 +- lib/Phpfastcache/Core/Item/CacheItemTrait.php | 13 +- .../Core/Pool/CacheItemPoolTrait.php | 34 +-- .../Core/Pool/DriverBaseTrait.php | 8 +- .../Core/Pool/ExtendedCacheItemPoolTrait.php | 8 +- .../Core/Pool/IO/IOHelperTrait.php | 16 +- lib/Phpfastcache/Drivers/Apcu/Driver.php | 1 - lib/Phpfastcache/Drivers/Cassandra/Driver.php | 1 - .../Drivers/Couchbasev3/Driver.php | 1 - lib/Phpfastcache/Drivers/Devnull/Driver.php | 1 - lib/Phpfastcache/Drivers/Devrandom/Driver.php | 1 - lib/Phpfastcache/Drivers/Files/Driver.php | 2 +- lib/Phpfastcache/Drivers/Memcache/Driver.php | 1 - lib/Phpfastcache/Drivers/Memcached/Driver.php | 1 - lib/Phpfastcache/Drivers/Memory/Driver.php | 1 - lib/Phpfastcache/Drivers/Memstatic/Config.php | 30 --- lib/Phpfastcache/Drivers/Memstatic/Driver.php | 33 --- lib/Phpfastcache/Drivers/Predis/Driver.php | 1 - lib/Phpfastcache/Drivers/Redis/Driver.php | 1 - .../Drivers/Rediscluster/Driver.php | 1 - lib/Phpfastcache/Drivers/Ssdb/Driver.php | 1 - lib/Phpfastcache/Drivers/Wincache/Config.php | 35 ---- lib/Phpfastcache/Drivers/Wincache/Driver.php | 119 ----------- lib/Phpfastcache/Drivers/Zenddisk/Driver.php | 1 - lib/Phpfastcache/Drivers/Zendshm/Driver.php | 1 - lib/Phpfastcache/Entities/DriverStatistic.php | 20 -- .../Event/AbstractItemEvent.php} | 21 +- .../Event/Event/AbstractItemPoolEvent.php | 36 ++++ .../Event/Event/AbstractStoppableEvent.php | 32 +++ .../Event/Event/CacheCommitItemEvent.php | 26 +++ .../CacheDriverCheckedEvent.php} | 11 +- .../Event/CacheDriverConnectedEvent.php} | 25 ++- .../Event/Event/CacheGetAllItemsEvent.php | 26 +++ .../Event/Event/CacheGetItemEvent.php | 27 +++ .../CacheGetItemInSlamBatchItemPoolEvent.php | 47 +++++ .../Event/Event/CacheItemEventTrait.php | 33 +++ .../Event/Event/CacheItemExpireAfterEvent.php | 38 ++++ .../Event/Event/CacheItemExpireAtEvent.php | 39 ++++ .../Event/CacheItemPoolEventClearItems.php | 26 +++ .../Event/CacheItemPoolEventClusterBuilt.php | 39 ++++ .../Event/CacheItemPoolEventDeleteItem.php | 26 +++ .../Event/CacheItemPoolEventDeleteItems.php | 26 +++ .../Event/CacheItemPoolEventGetItems.php | 28 +++ .../Event/CacheItemPoolEventSaveItem.php | 26 +++ ...heItemPoolReferenceParameterEventTrait.php | 35 ++++ .../CacheItemReferenceParameterEventTrait.php | 32 +++ .../Event/Event/CacheItemSetEvent.php | 26 +++ .../Event/Event/CacheItemsEventTrait.php | 40 ++++ ...plicationRandomPoolChosenItemPoolEvent.php | 41 ++++ ...eReplicationSlaveFallbackItemPoolEvent.php | 41 ++++ .../CacheSaveDeferredItemItemPoolEvent.php | 26 +++ .../CacheSaveMultipleItemsItemPoolEvent.php | 26 +++ .../CacheWriteFileOnDiskItemPoolEvent.php | 38 ++++ .../Event/Event/EventInterface.php | 29 +++ .../Event/EventManagerDispatcherInterface.php | 6 - .../Event/EventManagerDispatcherTrait.php | 9 - .../Event/EventManagerInterface.php | 44 +--- lib/Phpfastcache/Event/Events.php | 29 +++ .../Event/{Event.php => EventsInterface.php} | 16 +- lib/Phpfastcache/EventManager.php | 112 ++++++---- .../Helper/CacheConditionalHelper.php | 44 ---- tests/cases/EventManager.test.php | 19 +- tests/cases/EventManagerScoped.test.php | 12 +- tests/cases/GetAllItems.test.php | 4 +- 73 files changed, 1056 insertions(+), 786 deletions(-) delete mode 100644 lib/Phpfastcache/Config/Config.php delete mode 100644 lib/Phpfastcache/Drivers/Memstatic/Config.php delete mode 100644 lib/Phpfastcache/Drivers/Memstatic/Driver.php delete mode 100644 lib/Phpfastcache/Drivers/Wincache/Config.php delete mode 100644 lib/Phpfastcache/Drivers/Wincache/Driver.php rename lib/Phpfastcache/{Drivers/Wincache/Item.php => Event/Event/AbstractItemEvent.php} (50%) create mode 100644 lib/Phpfastcache/Event/Event/AbstractItemPoolEvent.php create mode 100644 lib/Phpfastcache/Event/Event/AbstractStoppableEvent.php create mode 100644 lib/Phpfastcache/Event/Event/CacheCommitItemEvent.php rename lib/Phpfastcache/Event/{EventInterface.php => Event/CacheDriverCheckedEvent.php} (64%) rename lib/Phpfastcache/{Drivers/Memstatic/Item.php => Event/Event/CacheDriverConnectedEvent.php} (51%) create mode 100644 lib/Phpfastcache/Event/Event/CacheGetAllItemsEvent.php create mode 100644 lib/Phpfastcache/Event/Event/CacheGetItemEvent.php create mode 100644 lib/Phpfastcache/Event/Event/CacheGetItemInSlamBatchItemPoolEvent.php create mode 100644 lib/Phpfastcache/Event/Event/CacheItemEventTrait.php create mode 100644 lib/Phpfastcache/Event/Event/CacheItemExpireAfterEvent.php create mode 100644 lib/Phpfastcache/Event/Event/CacheItemExpireAtEvent.php create mode 100644 lib/Phpfastcache/Event/Event/CacheItemPoolEventClearItems.php create mode 100644 lib/Phpfastcache/Event/Event/CacheItemPoolEventClusterBuilt.php create mode 100644 lib/Phpfastcache/Event/Event/CacheItemPoolEventDeleteItem.php create mode 100644 lib/Phpfastcache/Event/Event/CacheItemPoolEventDeleteItems.php create mode 100644 lib/Phpfastcache/Event/Event/CacheItemPoolEventGetItems.php create mode 100644 lib/Phpfastcache/Event/Event/CacheItemPoolEventSaveItem.php create mode 100644 lib/Phpfastcache/Event/Event/CacheItemPoolReferenceParameterEventTrait.php create mode 100644 lib/Phpfastcache/Event/Event/CacheItemReferenceParameterEventTrait.php create mode 100644 lib/Phpfastcache/Event/Event/CacheItemSetEvent.php create mode 100644 lib/Phpfastcache/Event/Event/CacheItemsEventTrait.php create mode 100644 lib/Phpfastcache/Event/Event/CacheReplicationRandomPoolChosenItemPoolEvent.php create mode 100644 lib/Phpfastcache/Event/Event/CacheReplicationSlaveFallbackItemPoolEvent.php create mode 100644 lib/Phpfastcache/Event/Event/CacheSaveDeferredItemItemPoolEvent.php create mode 100644 lib/Phpfastcache/Event/Event/CacheSaveMultipleItemsItemPoolEvent.php create mode 100644 lib/Phpfastcache/Event/Event/CacheWriteFileOnDiskItemPoolEvent.php create mode 100644 lib/Phpfastcache/Event/Event/EventInterface.php create mode 100644 lib/Phpfastcache/Event/Events.php rename lib/Phpfastcache/Event/{Event.php => EventsInterface.php} (83%) delete mode 100644 lib/Phpfastcache/Helper/CacheConditionalHelper.php diff --git a/.github/workflows/testsv2.yml b/.github/workflows/testsv2.yml index 98679d44..bdabf8d1 100644 --- a/.github/workflows/testsv2.yml +++ b/.github/workflows/testsv2.yml @@ -8,7 +8,7 @@ jobs: strategy: matrix: operating-system: [ubuntu-latest] - php-versions: ['8.0', '8.1', '8.2', '8.3'] + php-versions: ['8.2', '8.3'] name: PHP ${{ matrix.php-versions }} quality/tests on ${{ matrix.operating-system }} env: extensions: mbstring, intl, pdo_sqlite, json, redis, couchbase-3.2.2 diff --git a/CHANGELOG.md b/CHANGELOG.md index f818e3d8..44287a03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,189 +1,16 @@ -## 9.2.3 -##### 11 january 2024 -- __Drivers__ - - **Added support of `Ravendb` as an extension with its own [sub-repository](https://github.com/PHPSocialNetwork/ravendb-extension).** - - Deprecated `\Phpfastcache\Entities\DriverStatistic::getData()`. Will be removed as of v10. - - Deprecated `\Phpfastcache\Entities\DriverStatistic::setData()`. Will be removed as of v10. - - Added `\Phpfastcache\Entities\DriverStatistic::getCount(): int|null`. If applicable will return the count of cache objects stored in driver database/collection. Null otherwise. - - Added `\Phpfastcache\Entities\DriverStatistic::setCount()` - -## 9.2.2 -##### 11 january 2024 -- __Core__ - - Added optional prefix to `\Phpfastcache\Core\Pool\CacheItemPoolTrait::getKeys()` - -## 9.2.1 -##### 07 january 2024 -- __Misc__ - - Added additional check in cache manager for extensions - -## 9.2.0 -##### 07 january 2024 -- __API__ - - Upgraded Phpfastcache API to `4.3.0` ([see changes](CHANGELOG_API.md)) -- __Extensions__ (💡 New in 9.2) - - Created an extension mechanism to allow some drivers to be loaded independently, see [README.md](README.md) - - Added support of `Couchbasev4` as an extension with its own [sub-repository](https://github.com/PHPSocialNetwork/couchbasev4-extension). - - **IMPORTANT**: *AS OF v9.2* the following drivers has been **MOVED** to their own sub-repositories as a standalone extension: `Arangodb`, `Couchdb`, `Dynamodb`, `Firestore`, `Mongodb`, `Solr`. However `Couchbasev3` will stay in the core for compatibility reasons but will be deprecated. - - **IMPORTANT**: *AS OF v10* extensions will have their namespaces permanently moved from `Phpfastcache\Drivers\EXT_NAME\{Config, Driver, Event, Item}` to `Phpfastcache\Extensions\Drivers\EXT_NAME\{Config, Driver, Event, Item}`. For now an alias is ensuring compatibility. -- __Events__ - - EventManager is now scoped to its own poll if retrieved through `ExtendedCacheItemPoolTrait::->getEventManager()`. Global EventManager `EventManager::getInstance()` remains unchanged, see [EVENTS.md](./docs/EVENTS.md). - - `EventManagerInterface::on()` now also accepts a single `string $events`. - - Alias `\Phpfastcache\PhpfastcacheEventManager` of `\Phpfastcache\EventManager` has been added to improve your code import readability. - - Deprecated `\Phpfastcache\Event\EventManagerDispatcherInterface::hasEventManager` to be removed for v10. -- __Drivers__ - - Implemented #906 // **Added `RedisCluster` driver support** - - Driver `Memstatic` has changed its name to `Memory` for more consistency. - - Driver `Wincache` is now deprecated and will be removed as of v10 due to the lack of updates to PHP 8 [as officially stated by PHP](https://www.php.net/manual/en/install.windows.recommended.php). -- __Pool__ - - Added `ExtendedCacheItemPoolTrait::getAllItems` to allow you to retrieve all items in the cache. This method have some limitations, ([see more in the Wiki](https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV5%CB%96%5D-Fetching-all-keys)). -- __Core__ - - Configuration methods`ConfigurationOption::isPreventCacheSlams()`, `ConfigurationOption::setPreventCacheSlams()`, `ConfigurationOption::getCacheSlamsTimeout()`, `ConfigurationOption::setCacheSlamsTimeout()` are deprecated. ([See changes](CHANGELOG_API.md)). - - Fixed #907 // Internal "driver decode()" method will now throw an if the string data looks corrupted. - - Internal: Implemented multiple keys fetch (*if supported by the backend*) to improve the performances behind all `getItems()` calls. Currently only supported in some backends, but it may evolve in the future. - - Internal: Implemented multiple keys delete (*if supported by the backend*) to improve the performances behind all `deleteItems()` calls. Currently only supported in some backends, but it may evolve in the future. - - `\Phpfastcache\CacheContract::get()` now accepts a `\Stringable $cacheKey` argument. -- __Tags__ - - Added `\Phpfastcache\Core\Item\TaggableCacheItemInterface::isTagged(): bool` -- __Misc__ - - Fixed multiple code typo & updated README.md - -## 9.1.3 -##### 12 february 2023 -- __Core__ - - Fixed #893 // getItemsByTag() - empty after one item has expired -- __Misc__ - - Fixed multiple code typo & updated README.md - -## 9.1.2 -##### 09 june 2022 -- __API__ - - Upgraded Phpfastcache API to `4.2.0` ([see changes](CHANGELOG_API.md)) -- __Core__ - - Rewrote some core code to improve code maintainability & readability following Scrutinizer and Phpstan recommendations - - Fixed an issue with tags not properly reinitialized when a backend driver returns an expired cache item -- __Drivers__ - - Fixed #866 // Deprecated Method Cassandra\ExecutionOptions starting of Cassandra 1.3 -- __Misc__ - - Increased PHPSTAN level to 6 - - Fixed multiple fails of Travis CI - - Migrated Github issue templates from Markdown to YAML configurations - -## 9.1.1 -##### 15 april 2022 +## 10.0.0 +##### xx xxxxxxx xxxx - __Core__ - - Fixed #860 // Cache item throw an error on reading with DateTimeImmutable date objects - - Fixed an issue with tags not properly reinitialized when a backend driver returns an expired cache item -- __Drivers__ - - Fixed #862 // Multiple driver errors caused by invalid return type of `driverRead()` (reported by @ShockedPlot7560 and @aemla) - -## 9.1.0 -##### 04 april 2022 -- __API__ - - Upgraded Phpfastcache API to `4.1.0` ([see changes](CHANGELOG_API.md)) -- __Core__ - - Added `\Phpfastcache\Helper\UninstanciableObjectTrait` trait which will contains base locked constructor for any classes that are nor meant to be instanciated. - - Deprecated `\Phpfastcache\Config\Config::class` - - Removed/reworked/improved dead/unreachable/redundant/obsolete code, thanks to `Phpstan` -- __Drivers__ - - **Added `Solr` driver support** -- __Events__ - - Added `\Phpfastcache\Event\EventInterface` for `\Phpfastcache\Event\Event` and subclasses below - - Added `\Phpfastcache\Drivers\Arangodb\Event` for Arangodb events - - Added `\Phpfastcache\Drivers\Dynamodb\Event` for Dynamodb events - - Added `\Phpfastcache\Drivers\Solr\Event` for Solr events - - Moved the following constant from `\Phpfastcache\Event\Event` to their respective drivers: `ARANGODB_CONNECTION`, `ARANGODB_COLLECTION_PARAMS`, `DYNAMODB_CREATE_TABLE` -- __Cluster__ - - Fixed #855 // ClusterReplication drivers are saving erroneous expiration date in low-level backends -- __Misc__ - - Full PSR-12 compliance is now enforced by PHPCS - - Multiple typo fixes (@mbiebl) - - Updated composer suggestions and CI builder dependencies - -## 9.0.2 -##### 04 march 2022 -- __Core__ - - Updated CacheContract::__invoke() signature - - Added new option to allow EventManager override + improved EventManager tests (EventManager::setInstance()) -- __Drivers__ - - Fixed #853 // Configuration validation issue with Memcached socket (path) -- __Misc__ - - Fixed typo and some types hint - -## 9.0.1 -##### 14 november 2021 -- __Core__ - - Added `\Phpfastcache\Event\Event` class for centralizing event name with reusable constants. -- __Item__ - - `\Psr\Cache\CacheItemInterface::set` will also no longer accepts resource object anymore as method unique parameter -- __Misc__ - - Fixed typos in [README.md](./README.md) - -## 9.0.0 -##### 31 october 2021 -- __Migration guide__ - - Read the [migration guide](./docs/migration/MigratingFromV8ToV9.md) to upgrade from V8 to V9 -- __PSR-6__ - - Upgraded `psr/cache` dependency to `^2.0||^3.0` (for PHP-8 types) - - `\Psr\Cache\CacheItemInterface::get()` slightly changed to fully comply with missing PSR-6 specification: If the cache item is **NOT** hit, this method will return `NULL`. -- __PSR-16__ - - Upgraded `psr/simple-cache` dependency to `^2.0||^3.0` (for PHP-8 types) -- __API__ - - Upgraded Phpfastcache API to `4.0.0` ([see changes](CHANGELOG_API.md)) - - Renamed `Api::getPhpFastCacheVersion()` to `Api::getPhpfastcacheVersion()` - - Renamed `Api::getPhpFastCacheChangelog()` to `Api::getPhpfastcacheChangelog()` - - Renamed `Api::getPhpFastCacheGitHeadHash()` to `Api::getPhpfastcacheGitHeadHash()` -- __Cluster__ - - Renamed `\Phpfastcache\Cluster\AggregatorInterface::aggregateNewDriver()` to `\Phpfastcache\Cluster\AggregatorInterface::aggregateDriverByName()` -- __Exceptions__ - - Added `PhpfastcacheEventManagerException` for EventManager-related exceptions -- __Global__ - - Removed magics methods from CacheManager `CacheManager::DriverName()`, use `CacheManager::getInstance('DriverName')` instead - - `\Phpfastcache\Proxy\PhpfastcacheAbstractProxy` now implements `\Phpfastcache\Proxy\PhpfastcacheAbstractProxyInterface` - - Slightly increased performances on some critical points of the library - - Removed "BadPracticeOMeter" notice in CacheManager - - Removed many code duplicate (like in `\Phpfastcache\Driver\[DRIVER_NAME]\Item` classes) - - Reworked traits inter-dependencies for better logic and less polymorphic calls in pool/item traits - - Upgrading library to use benefits of PHP 8 new features (see below) - - Typed every class properties of the library - - Migrated many Closure to arrow functions - - Updated parameters & return type hint to use benefit of covariance and contravariance - - Removed embedded Autoload, Phpfastcache is now only Composer-compatible. - - Removed embedded dependencies (`psr/cache`, `psr/simple-cache`) + - Removed deprecated methods`ConfigurationOption::isPreventCacheSlams()`, `ConfigurationOption::setPreventCacheSlams()`, `ConfigurationOption::getCacheSlamsTimeout()`, `ConfigurationOption::setCacheSlamsTimeout()`. ([See changes](CHANGELOG_API.md)). + Removed deprecated class `\Phpfastcache\Config\Config::class`. - __Helpers__ - - Deprecated `\Phpfastcache\Helper\CacheConditionalHelper`, use `\Phpfastcache\CacheContract` instead - - The `\Phpfastcache\CacheContract` class is now also callable directly without calling `get()` method -- __Config/Options__ - - Configuration object will now be locked once the cache pool instance is running. - - Updated `ConfigurationOption` which is no longer an `ArrayObject` class, therefore array-syntax is no longer available. - - Removed configuration entry `htaccess` for files-based drivers. - - Removed `IOConfigurationOptionTrait::getHtaccess()` - - Removed `IOConfigurationOptionTrait::setHtaccess()` -- __Tests__ - - Added PHPMD, PHPCS and PHPSTAN coverages to increase quality of the project - - Updated tests to work with new core/drivers changes - - Removed Autoload test since its support has been removed and now only managed by Composer - - Increased tests reliability and code coverage for better catching any eventual regression -- __Item__ - - `\Psr\Cache\CacheItemInterface::set` will not accept `\Closure` object anymore as method unique parameter + - Removed `\Phpfastcache\Helper\CacheConditionalHelper`. Use `\Phpfastcache\CacheContract` instead. - __Drivers__ - - Added `Arangodb` driver support - - Added `Dynamodb` (AWS) driver support - - Added `Firestore` (GCP) driver support - - Removed `Cookie` driver because of its potential dangerosity - - Removed `Couchbase` (SDK 2 support dropped) driver which is now replaced by `Couchbasev3` (SDK 3) - - Removed `Devtrue` and `Devfalse` drivers - - Added `Devrandom` with configurable factor chance and data length - - Renamed classes `\Phpfastcache\Cluster\Drivers\[STATEGY]\[CLUSTER_NAME]Cluster` to `\Phpfastcache\Cluster\Drivers\[STATEGY]\Driver` for better driver naming across the project + - Removed deprecated method `\Phpfastcache\Entities\DriverStatistic::getData()`. + - Removed deprecated method `\Phpfastcache\Entities\DriverStatistic::setData()`. - __Events__ - - Added `\Phpfastcache\Event\EventReferenceParameter` class and more events such as driver-specific events, see [EVENTS.md](./docs/EVENTS.md) file for more information - - Event callbacks will now receive the `eventName` as an extra _last_ callback parameter (except for `onEveryEvents` callbacks) - - Added `EventManagerInterface::on(array $eventNames, $callback)` method, to subscribe to multiple events in once with the same callback - - Added method named `unbindAllEventCallbacks(): bool` to `EventManagerInterface` to allow you to unbind/clear all event from an event instance - - Updated argument type #2 (`$items`) of `onCacheSaveMultipleItems()` event from `ExtendedCacheItemInterface[]` to `EventReferenceParameter($items)` - - Updated argument type #2 (`$items`) of `onCacheCommitItem()` event from `ExtendedCacheItemInterface[]` to `EventReferenceParameter($items)` - - Updated argument type #2 (`$value`) of `onCacheItemSet()` event from `mixed` to `EventReferenceParameter(mixed $value)` -- __Misc__ - - Increased minimum PHP compatibility in composer to `^8.0` - - Updated copyright headers on every file to include the many project contributors - - Globally renamed every occurrence of `PhpFastCache` to `Phpcastcache` + - Phpfastcache EventManager is now [PSR-14](https://www.php-fig.org/psr/psr-14/) compliant. Therefore, its API has slightly changed and may not be backward-compatible. + - Removed deprecated method `\Phpfastcache\Event\EventManagerDispatcherInterface::hasEventManager`. +- __Drivers__ + - Removed driver `Memstatic`. Use `Memory` instead. + - Removed driver `Wincache`. diff --git a/composer.json b/composer.json index b9383c3c..7cd97859 100644 --- a/composer.json +++ b/composer.json @@ -6,7 +6,7 @@ "homepage": "https://www.phpfastcache.com", "license": "MIT", "readme": "README.md", - "minimum-stability": "stable", + "minimum-stability": "dev", "authors": [ { "name": "Georges.L", @@ -21,14 +21,16 @@ ], "provide": { "psr/cache-implementation": "2.0|3.0", - "psr/simple-cache-implementation": "2.0|3.0" + "psr/simple-cache-implementation": "2.0|3.0", + "psr/event-dispatcher-implementation": "^1.0" }, "require": { - "php": ">=8.0", + "php": ">=8.2", "psr/cache": "^2.0||^3.0", "psr/simple-cache": "^2.0||^3.0", "ext-mbstring": "*", - "ext-json": "*" + "ext-json": "*", + "psr/event-dispatcher": "^1.0" }, "require-dev": { "league/climate": "^3.8", @@ -37,7 +39,7 @@ "squizlabs/php_codesniffer": "@stable", "phpstan/phpstan": "@stable", "jetbrains/phpstorm-stubs": "dev-master", - "phpfastcache/phpfastcache-devtools": "dev-master" + "phpfastcache/phpfastcache-devtools": "^10.0.0-ALPHA" }, "suggest": { "ext-apcu": "*", diff --git a/lib/Phpfastcache/Cluster/ClusterAggregator.php b/lib/Phpfastcache/Cluster/ClusterAggregator.php index 6f080e01..cc6a2c91 100644 --- a/lib/Phpfastcache/Cluster/ClusterAggregator.php +++ b/lib/Phpfastcache/Cluster/ClusterAggregator.php @@ -19,7 +19,8 @@ use Exception; use Phpfastcache\CacheManager; use Phpfastcache\Config\ConfigurationOption; -use Phpfastcache\Event\Event; +use Phpfastcache\Event\Event\CacheItemPoolEventClusterBuilt; +use Phpfastcache\Event\Events; use Phpfastcache\EventManager; use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException; use Phpfastcache\Exceptions\PhpfastcacheDriverException; @@ -151,7 +152,7 @@ public function getCluster(int $strategy = AggregatorInterface::STRATEGY_FULL_RE ...\array_values($this->driverPools) ); - $this->cluster->getEventManager()->dispatch(Event::CACHE_CLUSTER_BUILT, $this, $this->cluster); + $this->cluster->getEventManager()->dispatch(new CacheItemPoolEventClusterBuilt($this->cluster, $this)); } } else { throw new PhpfastcacheInvalidArgumentException('Unknown cluster strategy'); diff --git a/lib/Phpfastcache/Cluster/ClusterPoolAbstract.php b/lib/Phpfastcache/Cluster/ClusterPoolAbstract.php index 029d1cba..1b23a0eb 100644 --- a/lib/Phpfastcache/Cluster/ClusterPoolAbstract.php +++ b/lib/Phpfastcache/Cluster/ClusterPoolAbstract.php @@ -235,16 +235,6 @@ public function getStats(): DriverStatistic ) ); - $stats->setData( - \implode( - ', ', - \array_map( - static fn (ExtendedCacheItemPoolInterface $pool) => $pool->getStats()->getData(), - $this->clusterPools - ) - ) - ); - return $stats; } } diff --git a/lib/Phpfastcache/Cluster/Drivers/MasterSlaveReplication/Driver.php b/lib/Phpfastcache/Cluster/Drivers/MasterSlaveReplication/Driver.php index 62be327d..ad3e524b 100644 --- a/lib/Phpfastcache/Cluster/Drivers/MasterSlaveReplication/Driver.php +++ b/lib/Phpfastcache/Cluster/Drivers/MasterSlaveReplication/Driver.php @@ -20,7 +20,7 @@ use Phpfastcache\Cluster\ClusterPoolAbstract; use Phpfastcache\Core\Item\ExtendedCacheItemInterface; use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; -use Phpfastcache\Event\Event; +use Phpfastcache\Event\Event\CacheReplicationSlaveFallbackItemPoolEvent; use Phpfastcache\Event\EventManagerInterface; use Phpfastcache\Exceptions\PhpfastcacheCoreException; use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException; @@ -80,9 +80,10 @@ protected function makeOperation(callable $operation) } catch (PhpfastcacheExceptionInterface $e) { try { $this->eventManager->dispatch( - Event::CACHE_REPLICATION_SLAVE_FALLBACK, - $this, - \debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function'] + new CacheReplicationSlaveFallbackItemPoolEvent( + $this, + \debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function'] + ) ); return $operation($this->getSlavePool()); } catch (PhpfastcacheExceptionInterface $e) { diff --git a/lib/Phpfastcache/Cluster/Drivers/RandomReplication/Driver.php b/lib/Phpfastcache/Cluster/Drivers/RandomReplication/Driver.php index 5f688b16..76db8d89 100644 --- a/lib/Phpfastcache/Cluster/Drivers/RandomReplication/Driver.php +++ b/lib/Phpfastcache/Cluster/Drivers/RandomReplication/Driver.php @@ -18,7 +18,8 @@ use Phpfastcache\Cluster\AggregatablePoolInterface; use Phpfastcache\Cluster\Drivers\MasterSlaveReplication\Driver as MasterSlaveReplicationDriver; -use Phpfastcache\Event\Event; +use Phpfastcache\Event\Event\CacheReplicationRandomPoolChosenItemPoolEvent; +use Phpfastcache\Event\Events; use Phpfastcache\Event\EventManagerInterface; use ReflectionException; use ReflectionMethod; @@ -46,9 +47,10 @@ public function __construct( $randomPool = $driverPools[\random_int(0, \count($driverPools) - 1)]; $this->eventManager->dispatch( - Event::CACHE_REPLICATION_RANDOM_POOL_CHOSEN, - $this, - $randomPool + new CacheReplicationRandomPoolChosenItemPoolEvent( + $this, + $randomPool + ) ); $this->clusterPools = [$randomPool]; diff --git a/lib/Phpfastcache/Config/Config.php b/lib/Phpfastcache/Config/Config.php deleted file mode 100644 index ee18de6b..00000000 --- a/lib/Phpfastcache/Config/Config.php +++ /dev/null @@ -1,36 +0,0 @@ - - * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors - */ - -declare(strict_types=1); - -namespace Phpfastcache\Config; - -/** - * @deprecated This class is deprecated and will be removed in v10, use ConfigurationOption instead - */ -class Config extends ConfigurationOption -{ - public function __construct(array $parameters = []) - { - \trigger_error( - \sprintf( - '%s class is deprecated and will be removed in v10, use %s instead.', - self::class, - ConfigurationOption::class - ), - \E_USER_DEPRECATED - ); - parent::__construct($parameters); - } -} diff --git a/lib/Phpfastcache/Config/ConfigurationOption.php b/lib/Phpfastcache/Config/ConfigurationOption.php index d3981f83..99744310 100644 --- a/lib/Phpfastcache/Config/ConfigurationOption.php +++ b/lib/Phpfastcache/Config/ConfigurationOption.php @@ -41,10 +41,6 @@ class ConfigurationOption extends AbstractConfigurationOption implements Configu protected string $path = ''; - protected bool $preventCacheSlams = false; - - protected int $cacheSlamsTimeout = 15; - protected bool $useStaticItemCaching = true; protected ?object $superGlobalAccessor = null; @@ -231,63 +227,6 @@ public function setPath(string $path): static return $this; } - /** - * @deprecated This method is deprecated and will be soon moved to IOConfigurationOption class, which means they will only be available for `IO` drivers. - * @return bool - */ - public function isPreventCacheSlams(): bool - { - return $this->preventCacheSlams; - } - - /** - * @deprecated This method is deprecated and will be soon moved to IOConfigurationOption class, which means they will only be available for `IO` drivers. - * @param bool $preventCacheSlams - * @return ConfigurationOption - * @throws PhpfastcacheLogicException - */ - public function setPreventCacheSlams(bool $preventCacheSlams): static - { - if ($preventCacheSlams !== $this->preventCacheSlams) { - trigger_error( - 'This method is deprecated and will be soon moved to IOConfigurationOption class, which means they will only be available for `IO` drivers.', - E_USER_DEPRECATED - ); - } - - $this->enforceLockedProperty(__FUNCTION__); - $this->preventCacheSlams = $preventCacheSlams; - return $this; - } - - /** - * @deprecated This method is deprecated and will be soon moved to IOConfigurationOption class, which means they will only be available for `IO` drivers. - * @return int - */ - public function getCacheSlamsTimeout(): int - { - return $this->cacheSlamsTimeout; - } - - /** - * @deprecated This method is deprecated and will be soon moved to IOConfigurationOption class, which means they will only be available for `IO` drivers. - * @param int $cacheSlamsTimeout - * @return ConfigurationOption - * @throws PhpfastcacheLogicException - */ - public function setCacheSlamsTimeout(int $cacheSlamsTimeout): static - { - if ($cacheSlamsTimeout !== $this->cacheSlamsTimeout) { - trigger_error( - 'This method is deprecated and will be soon moved to IOConfigurationOption class, which means they will only be available for `IO` drivers.', - E_USER_DEPRECATED - ); - } - $this->enforceLockedProperty(__FUNCTION__); - $this->cacheSlamsTimeout = $cacheSlamsTimeout; - return $this; - } - /** * @return bool */ diff --git a/lib/Phpfastcache/Config/IOConfigurationOption.php b/lib/Phpfastcache/Config/IOConfigurationOption.php index f72e3939..b3260e35 100644 --- a/lib/Phpfastcache/Config/IOConfigurationOption.php +++ b/lib/Phpfastcache/Config/IOConfigurationOption.php @@ -19,9 +19,6 @@ use Phpfastcache\Exceptions\PhpfastcacheInvalidConfigurationException; use Phpfastcache\Exceptions\PhpfastcacheLogicException; -/** - * @todo: As of V10, imports cache slams properties. - */ class IOConfigurationOption extends ConfigurationOption { protected bool $secureFileManipulation = false; @@ -32,6 +29,10 @@ class IOConfigurationOption extends ConfigurationOption protected int $defaultChmod = 0777; + protected bool $preventCacheSlams = false; + + protected int $cacheSlamsTimeout = 15; + /** * @return string */ diff --git a/lib/Phpfastcache/Core/Item/CacheItemTrait.php b/lib/Phpfastcache/Core/Item/CacheItemTrait.php index 2d2d24b6..122e5c8a 100644 --- a/lib/Phpfastcache/Core/Item/CacheItemTrait.php +++ b/lib/Phpfastcache/Core/Item/CacheItemTrait.php @@ -19,7 +19,10 @@ use DateInterval; use DateTime; use DateTimeInterface; -use Phpfastcache\Event\Event; +use Phpfastcache\Event\Event\CacheItemSetEvent; +use Phpfastcache\Event\Event\CacheItemExpireAfterEvent; +use Phpfastcache\Event\Event\CacheItemExpireAtEvent; +use Phpfastcache\Event\Events; use Phpfastcache\Event\EventManagerDispatcherTrait; use Phpfastcache\Event\EventReferenceParameter; use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException; @@ -69,7 +72,7 @@ public function set(mixed $value): static throw new PhpfastcacheInvalidArgumentException('The value set cannot be a resource'); } - $this->eventManager->dispatch(Event::CACHE_ITEM_SET, $this, new EventReferenceParameter($value, true)); + $this->eventManager->dispatch(new CacheItemSetEvent($this, new EventReferenceParameter($value, true))); $this->data = $value; @@ -101,7 +104,7 @@ public function setHit(bool $isHit): ExtendedCacheItemInterface public function expiresAt(?\DateTimeInterface $expiration): static { if ($expiration instanceof DateTimeInterface) { - $this->eventManager->dispatch(Event::CACHE_ITEM_EXPIRE_AT, $this, $expiration); + $this->eventManager->dispatch(new CacheItemExpireAtEvent($this, $expiration)); $this->expirationDate = $this->demutateDatetime($expiration); } else { throw new PhpfastcacheInvalidArgumentException('$expiration must be an object implementing the DateTimeInterface got: ' . \gettype($expiration)); @@ -126,11 +129,11 @@ public function expiresAfter(int|\DateInterval|null $time): static $time = 30 * 24 * 3600 * 5; } - $this->eventManager->dispatch(Event::CACHE_ITEM_EXPIRE_AFTER, $this, $time); + $this->eventManager->dispatch(new CacheItemExpireAfterEvent($this, $time)); $this->expirationDate = (new DateTime())->add(new DateInterval(\sprintf('PT%dS', $time))); } elseif ($time instanceof DateInterval) { - $this->eventManager->dispatch(Event::CACHE_ITEM_EXPIRE_AFTER, $this, $time); + $this->eventManager->dispatch(new CacheItemExpireAfterEvent($this, $time)); $this->expirationDate = (new DateTime())->add($time); } else { diff --git a/lib/Phpfastcache/Core/Pool/CacheItemPoolTrait.php b/lib/Phpfastcache/Core/Pool/CacheItemPoolTrait.php index a66e99c1..d533ac21 100644 --- a/lib/Phpfastcache/Core/Pool/CacheItemPoolTrait.php +++ b/lib/Phpfastcache/Core/Pool/CacheItemPoolTrait.php @@ -22,7 +22,16 @@ use Phpfastcache\Core\Item\ExtendedCacheItemInterface; use Phpfastcache\Entities\DriverIO; use Phpfastcache\Entities\ItemBatch; -use Phpfastcache\Event\Event; +use Phpfastcache\Event\Event\CacheGetItemInSlamBatchItemPoolEvent; +use Phpfastcache\Event\Event\CacheItemPoolEventClearItems; +use Phpfastcache\Event\Event\CacheCommitItemEvent; +use Phpfastcache\Event\Event\CacheItemPoolEventDeleteItem; +use Phpfastcache\Event\Event\CacheItemPoolEventDeleteItems; +use Phpfastcache\Event\Event\CacheGetItemEvent; +use Phpfastcache\Event\Event\CacheItemPoolEventGetItems; +use Phpfastcache\Event\Event\CacheSaveDeferredItemItemPoolEvent; +use Phpfastcache\Event\Event\CacheItemPoolEventSaveItem; +use Phpfastcache\Event\Events; use Phpfastcache\Event\EventManagerInterface; use Phpfastcache\Event\EventReferenceParameter; use Phpfastcache\Exceptions\PhpfastcacheCoreException; @@ -104,12 +113,13 @@ public function setItem(CacheItemInterface $item): static public function getItems(array $keys = []): iterable { $items = []; + $config = $this->getConfig(); /** * Usually, drivers that are able to enable cache slams * does not benefit of driverReadMultiple() call. */ - if (!$this->getConfig()->isPreventCacheSlams()) { + if (!($config instanceof IOConfigurationOptionInterface) || !$config->isPreventCacheSlams()) { $this->validateCacheKeys(...$keys); /** @@ -182,7 +192,7 @@ public function getItems(array $keys = []): iterable return $collection; } - $this->eventManager->dispatch(Event::CACHE_GET_ITEMS, $this, $items); + $this->eventManager->dispatch(new CacheItemPoolEventGetItems($this, $items)); return $items; } @@ -233,10 +243,10 @@ public function getItem(string $key): ExtendedCacheItemInterface return; } - $this->eventManager->dispatch(Event::CACHE_GET_ITEM_IN_SLAM_BATCH, $this, $driverData, $cacheSlamsSpendSeconds); + $this->eventManager->dispatch(new CacheGetItemInSlamBatchItemPoolEvent($this, $driverData, $cacheSlamsSpendSeconds)); /** - * Wait for a second before + * Wait for a 1/10 second before * attempting to get exit * the current batch process */ @@ -270,7 +280,7 @@ public function getItem(string $key): ExtendedCacheItemInterface $item = $this->itemInstances[$key]; } - $this->eventManager->dispatch(Event::CACHE_GET_ITEM, $this, $item); + $this->eventManager->dispatch(new CacheGetItemEvent($this, $item)); $item->isHit() ? $this->getIO()->incReadHit() : $this->getIO()->incReadMiss(); @@ -299,7 +309,7 @@ public function hasItem(string $key): bool */ public function clear(): bool { - $this->eventManager->dispatch(Event::CACHE_CLEAR_ITEM, $this, $this->itemInstances); + $this->eventManager->dispatch(new CacheItemPoolEventClearItems($this, $this->itemInstances)); $this->getIO()->incWriteHit(); // Faster than detachAllItems() @@ -330,7 +340,7 @@ public function deleteItems(array $keys): bool } } $this->getIO()->incWriteHit(); - $this->eventManager->dispatch(Event::CACHE_DELETE_ITEMS, $this, $items); + $this->eventManager->dispatch(new CacheItemPoolEventDeleteItems($this, $items)); $this->deregisterItems($keys); } catch (PhpfastcacheUnsupportedMethodException) { foreach ($keys as $key) { @@ -368,7 +378,7 @@ public function deleteItem(string $key): bool $item->setHit(false); $this->getIO()->incWriteHit(); - $this->eventManager->dispatch(Event::CACHE_DELETE_ITEM, $this, $item); + $this->eventManager->dispatch(new CacheItemPoolEventDeleteItem($this, $item)); /** * De-register the item instance @@ -402,7 +412,7 @@ public function saveDeferred(CacheItemInterface $item): bool throw new RuntimeException('Spl object hash mismatches ! You probably tried to save a detached item which has been already retrieved from cache.'); } - $this->eventManager->dispatch(Event::CACHE_SAVE_DEFERRED_ITEM, $this, $item); + $this->eventManager->dispatch(new CacheSaveDeferredItemItemPoolEvent($this, $item)); $this->deferredList[$item->getKey()] = $item; return true; @@ -417,7 +427,7 @@ public function saveDeferred(CacheItemInterface $item): bool */ public function commit(): bool { - $this->eventManager->dispatch(Event::CACHE_COMMIT_ITEM, $this, new EventReferenceParameter($this->deferredList)); + $this->eventManager->dispatch(new CacheCommitItemEvent($this, new EventReferenceParameter($this->deferredList))); if (\count($this->deferredList)) { $return = true; @@ -462,7 +472,7 @@ public function save(CacheItemInterface $item): bool } $this->assertCacheItemType($item, self::getItemClass()); - $this->eventManager->dispatch(Event::CACHE_SAVE_ITEM, $this, $item); + $this->eventManager->dispatch(new CacheItemPoolEventSaveItem($this, $item)); if ($this->getConfig() instanceof IOConfigurationOptionInterface && $this->getConfig()->isPreventCacheSlams()) { /** diff --git a/lib/Phpfastcache/Core/Pool/DriverBaseTrait.php b/lib/Phpfastcache/Core/Pool/DriverBaseTrait.php index 1f3d85e2..fc45ffb1 100644 --- a/lib/Phpfastcache/Core/Pool/DriverBaseTrait.php +++ b/lib/Phpfastcache/Core/Pool/DriverBaseTrait.php @@ -19,7 +19,9 @@ use DateTime; use DateTimeInterface; use Phpfastcache\Config\ConfigurationOptionInterface; -use Phpfastcache\Event\Event; +use Phpfastcache\Event\Event\CacheDriverCheckedEvent; +use Phpfastcache\Event\Event\CacheDriverConnectedEvent; +use Phpfastcache\Event\Events; use Phpfastcache\Event\EventManagerDispatcherTrait; use Phpfastcache\Event\EventManagerInterface; use Phpfastcache\Exceptions\PhpfastcacheCorruptedDataException; @@ -85,12 +87,12 @@ public function __construct(#[\SensitiveParameter] ConfigurationOptionInterface ) ); } - $this->eventManager->dispatch(Event::CACHE_DRIVER_CHECKED, $this); + $this->eventManager->dispatch(new CacheDriverCheckedEvent($this)); try { $this->driverConnect(); $config->lock($this); // Lock the config only after a successful driver connection. - $this->eventManager->dispatch(Event::CACHE_DRIVER_CONNECTED, $this, $this->instance ?? null); + $this->eventManager->dispatch(new CacheDriverConnectedEvent($this, $this->instance ?? null)); } catch (Throwable $e) { throw new PhpfastcacheDriverConnectException( sprintf( diff --git a/lib/Phpfastcache/Core/Pool/ExtendedCacheItemPoolTrait.php b/lib/Phpfastcache/Core/Pool/ExtendedCacheItemPoolTrait.php index 6ecec657..725293cd 100644 --- a/lib/Phpfastcache/Core/Pool/ExtendedCacheItemPoolTrait.php +++ b/lib/Phpfastcache/Core/Pool/ExtendedCacheItemPoolTrait.php @@ -17,7 +17,9 @@ namespace Phpfastcache\Core\Pool; use Phpfastcache\Core\Item\ExtendedCacheItemInterface; -use Phpfastcache\Event\Event; +use Phpfastcache\Event\Event\CacheGetAllItemsEvent; +use Phpfastcache\Event\Event\CacheSaveMultipleItemsItemPoolEvent; +use Phpfastcache\Event\Events; use Phpfastcache\Event\EventReferenceParameter; use Phpfastcache\Exceptions\PhpfastcacheCoreException; use Phpfastcache\Exceptions\PhpfastcacheDriverException; @@ -43,7 +45,7 @@ public function getAllItems(string $pattern = ''): iterable * This event allow you to customize the callback and wrap it to an invoker * like SebastianBergmann\Invoke\Invoke, so you can set up custom timeouts. */ - $this->eventManager->dispatch(Event::CACHE_GET_ALL_ITEMS, $this, new EventReferenceParameter($driverReadAllKeysCallback)); + $this->eventManager->dispatch(new CacheGetAllItemsEvent($this, new EventReferenceParameter($driverReadAllKeysCallback))); $keys = $driverReadAllKeysCallback($pattern); if (count($keys) > 0) { @@ -100,7 +102,7 @@ public function detachItem(CacheItemInterface $item): static */ public function saveMultiple(ExtendedCacheItemInterface ...$items): bool { - $this->eventManager->dispatch(Event::CACHE_SAVE_MULTIPLE_ITEMS, $this, new EventReferenceParameter($items)); + $this->eventManager->dispatch(new CacheSaveMultipleItemsItemPoolEvent($this, new EventReferenceParameter($items))); if (\count($items)) { foreach ($items as $item) { diff --git a/lib/Phpfastcache/Core/Pool/IO/IOHelperTrait.php b/lib/Phpfastcache/Core/Pool/IO/IOHelperTrait.php index 296f4d6e..3e04c7f7 100644 --- a/lib/Phpfastcache/Core/Pool/IO/IOHelperTrait.php +++ b/lib/Phpfastcache/Core/Pool/IO/IOHelperTrait.php @@ -19,7 +19,8 @@ use Phpfastcache\Config\IOConfigurationOptionInterface; use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait; use Phpfastcache\Entities\DriverStatistic; -use Phpfastcache\Event\Event; +use Phpfastcache\Event\Event\CacheWriteFileOnDiskItemPoolEvent; +use Phpfastcache\Event\Events; use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException; use Phpfastcache\Exceptions\PhpfastcacheIOException; use Phpfastcache\Util\Directory; @@ -60,12 +61,6 @@ public function getStats(): DriverStatistic ] ); - if ($this->getConfig()->isUseStaticItemCaching()) { - $stat->setData(implode(', ', \array_keys($this->itemInstances))); - } else { - $stat->setData('No data available since static item caching option (useStaticItemCaching) is disabled.'); - } - return $stat; } @@ -274,16 +269,15 @@ protected function readFile(string $file): string /** * @param string $file * @param string $data - * @param bool $secureFileManipulation * @return bool * @throws PhpfastcacheIOException * @throws \Exception */ - protected function writeFile(string $file, string $data, bool $secureFileManipulation = false): bool + protected function writeFile(string $file, string $data): bool { - $this->eventManager->dispatch(Event::CACHE_WRITE_FILE_ON_DISK, $this, $file, $secureFileManipulation); + $this->eventManager->dispatch(new CacheWriteFileOnDiskItemPoolEvent($this, $file)); - if ($secureFileManipulation) { + if ($this->getConfig()->isSecureFileManipulation()) { $tmpFilename = Directory::getAbsolutePath( dirname($file) . \DIRECTORY_SEPARATOR . 'tmp_' . $this->getConfig()->getDefaultFileNameHashFunction()( \bin2hex(\random_bytes(16)) diff --git a/lib/Phpfastcache/Drivers/Apcu/Driver.php b/lib/Phpfastcache/Drivers/Apcu/Driver.php index 73d214b8..0fdf3b4f 100644 --- a/lib/Phpfastcache/Drivers/Apcu/Driver.php +++ b/lib/Phpfastcache/Drivers/Apcu/Driver.php @@ -52,7 +52,6 @@ public function getStats(): DriverStatistic $date = (new DateTime())->setTimestamp($stats['start_time']); return (new DriverStatistic()) - ->setData(implode(', ', array_keys($this->itemInstances))) ->setInfo( sprintf( "The APCU cache is up since %s, and have %d item(s) in cache.\n For more information see RawData.", diff --git a/lib/Phpfastcache/Drivers/Cassandra/Driver.php b/lib/Phpfastcache/Drivers/Cassandra/Driver.php index 54c4c5b6..099b4863 100644 --- a/lib/Phpfastcache/Drivers/Cassandra/Driver.php +++ b/lib/Phpfastcache/Drivers/Cassandra/Driver.php @@ -299,7 +299,6 @@ public function getStats(): DriverStatistic return (new DriverStatistic()) ->setSize($result->first()['cache_size']) ->setRawData([]) - ->setData(implode(', ', array_keys($this->itemInstances))) ->setInfo('The cache size represents only the cache data itself without counting data structures associated to the cache entries.'); } diff --git a/lib/Phpfastcache/Drivers/Couchbasev3/Driver.php b/lib/Phpfastcache/Drivers/Couchbasev3/Driver.php index 15a19cc6..edd726a6 100644 --- a/lib/Phpfastcache/Drivers/Couchbasev3/Driver.php +++ b/lib/Phpfastcache/Drivers/Couchbasev3/Driver.php @@ -217,7 +217,6 @@ public function getStats(): DriverStatistic return (new DriverStatistic()) ->setSize(0) ->setRawData($info) - ->setData(implode(', ', array_keys($this->itemInstances))) ->setInfo($info['sdk'] . "\n For more information see RawData."); } diff --git a/lib/Phpfastcache/Drivers/Devnull/Driver.php b/lib/Phpfastcache/Drivers/Devnull/Driver.php index aa47640b..8d7a4996 100644 --- a/lib/Phpfastcache/Drivers/Devnull/Driver.php +++ b/lib/Phpfastcache/Drivers/Devnull/Driver.php @@ -47,7 +47,6 @@ public function getStats(): DriverStatistic $stat = new DriverStatistic(); $stat->setInfo('[Devnull] A void info string') ->setSize(0) - ->setData(implode(', ', array_keys($this->itemInstances))) ->setRawData(null); return $stat; diff --git a/lib/Phpfastcache/Drivers/Devrandom/Driver.php b/lib/Phpfastcache/Drivers/Devrandom/Driver.php index 24cc7375..f2dc4561 100644 --- a/lib/Phpfastcache/Drivers/Devrandom/Driver.php +++ b/lib/Phpfastcache/Drivers/Devrandom/Driver.php @@ -48,7 +48,6 @@ public function getStats(): DriverStatistic $stat = new DriverStatistic(); $stat->setInfo('[Devrandom] A void info string') ->setSize(0) - ->setData(implode(', ', array_keys($this->itemInstances))) ->setRawData(false); return $stat; diff --git a/lib/Phpfastcache/Drivers/Files/Driver.php b/lib/Phpfastcache/Drivers/Files/Driver.php index 87782ce0..c114f0a7 100644 --- a/lib/Phpfastcache/Drivers/Files/Driver.php +++ b/lib/Phpfastcache/Drivers/Files/Driver.php @@ -88,7 +88,7 @@ protected function driverWrite(ExtendedCacheItemInterface $item): bool $data = $this->encode($this->driverPreWrap($item)); try { - return $this->writeFile($filePath, $data, $this->getConfig()->isSecureFileManipulation()); + return $this->writeFile($filePath, $data); } catch (Exception) { return false; } diff --git a/lib/Phpfastcache/Drivers/Memcache/Driver.php b/lib/Phpfastcache/Drivers/Memcache/Driver.php index b4445227..da2ea360 100644 --- a/lib/Phpfastcache/Drivers/Memcache/Driver.php +++ b/lib/Phpfastcache/Drivers/Memcache/Driver.php @@ -86,7 +86,6 @@ public function getStats(): DriverStatistic $date = (new DateTime())->setTimestamp(time() - $stats['uptime']); return (new DriverStatistic()) - ->setData(implode(', ', array_keys($this->itemInstances))) ->setInfo(sprintf("The memcache daemon v%s is up since %s.\n For more information see RawData.", $stats['version'], $date->format(DATE_RFC2822))) ->setRawData($stats) ->setSize((int)$stats['bytes']); diff --git a/lib/Phpfastcache/Drivers/Memcached/Driver.php b/lib/Phpfastcache/Drivers/Memcached/Driver.php index 9c70367b..b9706963 100644 --- a/lib/Phpfastcache/Drivers/Memcached/Driver.php +++ b/lib/Phpfastcache/Drivers/Memcached/Driver.php @@ -85,7 +85,6 @@ public function getStats(): DriverStatistic $date = (new DateTime())->setTimestamp(time() - $stats['uptime']); return (new DriverStatistic()) - ->setData(implode(', ', array_keys($this->itemInstances))) ->setInfo(sprintf("The memcache daemon v%s is up since %s.\n For more information see RawData.", $stats['version'], $date->format(DATE_RFC2822))) ->setRawData($stats) ->setSize((int)$stats['bytes']); diff --git a/lib/Phpfastcache/Drivers/Memory/Driver.php b/lib/Phpfastcache/Drivers/Memory/Driver.php index 218f8aa1..72c26563 100644 --- a/lib/Phpfastcache/Drivers/Memory/Driver.php +++ b/lib/Phpfastcache/Drivers/Memory/Driver.php @@ -120,7 +120,6 @@ public function getStats(): DriverStatistic $stat = new DriverStatistic(); $stat->setInfo('[Memstatic] A memory static driver') ->setSize(mb_strlen(serialize($this->staticStack))) - ->setData(implode(', ', array_keys($this->itemInstances))) ->setRawData($this->staticStack); return $stat; diff --git a/lib/Phpfastcache/Drivers/Memstatic/Config.php b/lib/Phpfastcache/Drivers/Memstatic/Config.php deleted file mode 100644 index 94a88be3..00000000 --- a/lib/Phpfastcache/Drivers/Memstatic/Config.php +++ /dev/null @@ -1,30 +0,0 @@ - - * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors - */ - -declare(strict_types=1); - -namespace Phpfastcache\Drivers\Memstatic; - -/** - * @deprecated Memstatic driver has changed its name, it is now called "Memory". - * @see \Phpfastcache\Drivers\Memory\Config - */ -class Config extends \Phpfastcache\Drivers\Memory\Config -{ - public function __construct(array $parameters = []) - { - trigger_error('Memstatic driver has changed its name, it is now called "Memory"', E_USER_DEPRECATED); - parent::__construct($parameters); - } -} diff --git a/lib/Phpfastcache/Drivers/Memstatic/Driver.php b/lib/Phpfastcache/Drivers/Memstatic/Driver.php deleted file mode 100644 index 6f161b53..00000000 --- a/lib/Phpfastcache/Drivers/Memstatic/Driver.php +++ /dev/null @@ -1,33 +0,0 @@ - - * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors - */ - -declare(strict_types=1); - -namespace Phpfastcache\Drivers\Memstatic; - -use Phpfastcache\Config\ConfigurationOptionInterface; -use Phpfastcache\Event\EventManagerInterface; - -/** - * @deprecated Memstatic driver has changed its name, it is now called "Memory". - * @see \Phpfastcache\Drivers\Memory\Driver - */ -class Driver extends \Phpfastcache\Drivers\Memory\Driver -{ - public function __construct(#[\SensitiveParameter] ConfigurationOptionInterface $config, string $instanceId, EventManagerInterface $em) - { - trigger_error('Memstatic driver has changed its name, it is now called "Memory"', E_USER_DEPRECATED); - parent::__construct($config, $instanceId, $em); - } -} diff --git a/lib/Phpfastcache/Drivers/Predis/Driver.php b/lib/Phpfastcache/Drivers/Predis/Driver.php index c00f47ac..6e027070 100644 --- a/lib/Phpfastcache/Drivers/Predis/Driver.php +++ b/lib/Phpfastcache/Drivers/Predis/Driver.php @@ -73,7 +73,6 @@ public function getStats(): DriverStatistic $date = (isset($info['Server']['uptime_in_seconds']) ? (new DateTime())->setTimestamp(time() - $info['Server']['uptime_in_seconds']) : 'unknown date'); return (new DriverStatistic()) - ->setData(implode(', ', array_keys($this->itemInstances))) ->setRawData($info) ->setSize((int)$size) ->setInfo( diff --git a/lib/Phpfastcache/Drivers/Redis/Driver.php b/lib/Phpfastcache/Drivers/Redis/Driver.php index 49d5e21f..f9b0d151 100644 --- a/lib/Phpfastcache/Drivers/Redis/Driver.php +++ b/lib/Phpfastcache/Drivers/Redis/Driver.php @@ -54,7 +54,6 @@ public function getStats(): DriverStatistic $date = (new DateTime())->setTimestamp(time() - $info['uptime_in_seconds']); return (new DriverStatistic()) - ->setData(implode(', ', array_keys($this->itemInstances))) ->setRawData($info) ->setSize((int)$info['used_memory_dataset']) ->setInfo( diff --git a/lib/Phpfastcache/Drivers/Rediscluster/Driver.php b/lib/Phpfastcache/Drivers/Rediscluster/Driver.php index 54b8afb0..662d2ee6 100644 --- a/lib/Phpfastcache/Drivers/Rediscluster/Driver.php +++ b/lib/Phpfastcache/Drivers/Rediscluster/Driver.php @@ -54,7 +54,6 @@ public function getStats(): DriverStatistic $date = (new DateTime())->setTimestamp(time() - min(array_column($infos, 'uptime_in_seconds'))); return (new DriverStatistic()) - ->setData(implode(', ', array_keys($this->itemInstances))) ->setRawData($infos) ->setSize(array_sum(array_column($infos, 'used_memory_dataset'))) ->setInfo( diff --git a/lib/Phpfastcache/Drivers/Ssdb/Driver.php b/lib/Phpfastcache/Drivers/Ssdb/Driver.php index 3c7067d5..e21f8bf7 100644 --- a/lib/Phpfastcache/Drivers/Ssdb/Driver.php +++ b/lib/Phpfastcache/Drivers/Ssdb/Driver.php @@ -61,7 +61,6 @@ public function getStats(): DriverStatistic */ $stat->setInfo(sprintf("Ssdb-server v%s with a total of %s call(s).\n For more information see RawData.", $info[2], $info[6])) ->setRawData($info) - ->setData(implode(', ', array_keys($this->itemInstances))) ->setSize($this->instance->dbsize()); return $stat; diff --git a/lib/Phpfastcache/Drivers/Wincache/Config.php b/lib/Phpfastcache/Drivers/Wincache/Config.php deleted file mode 100644 index 5b33a9f3..00000000 --- a/lib/Phpfastcache/Drivers/Wincache/Config.php +++ /dev/null @@ -1,35 +0,0 @@ - - * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors - */ - -declare(strict_types=1); - -namespace Phpfastcache\Drivers\Wincache; - -use Phpfastcache\Config\ConfigurationOption; - -/** - * @deprecated will be removed as of v10 due to the lack of updates to PHP8 as officially stated by PHP: https://www.php.net/manual/en/install.windows.recommended.php - */ -class Config extends ConfigurationOption -{ - public function __construct(array $parameters = []) - { - trigger_error( - 'Wincache is now deprecated and will be removed as of v10 due to the lack of updates to PHP8 as officially stated by PHP: - https://www.php.net/manual/en/install.windows.recommended.php', - E_USER_DEPRECATED - ); - parent::__construct($parameters); - } -} diff --git a/lib/Phpfastcache/Drivers/Wincache/Driver.php b/lib/Phpfastcache/Drivers/Wincache/Driver.php deleted file mode 100644 index 111aae8e..00000000 --- a/lib/Phpfastcache/Drivers/Wincache/Driver.php +++ /dev/null @@ -1,119 +0,0 @@ - - * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors - */ - -declare(strict_types=1); - -namespace Phpfastcache\Drivers\Wincache; - -use DateTime; -use Phpfastcache\Cluster\AggregatablePoolInterface; -use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; -use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait; -use Phpfastcache\Core\Item\ExtendedCacheItemInterface; -use Phpfastcache\Entities\DriverStatistic; -use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException; -use Phpfastcache\Exceptions\PhpfastcacheLogicException; - -/** - * @deprecated will be removed as of v10 due to the lack of updates to PHP8 as officially stated by PHP: https://www.php.net/manual/en/install.windows.recommended.php - * @method Config getConfig() - */ -class Driver implements AggregatablePoolInterface -{ - use TaggableCacheItemPoolTrait; - - /** - * @return bool - */ - public function driverCheck(): bool - { - return extension_loaded('wincache') && function_exists('wincache_ucache_set'); - } - - public function getHelp(): string - { - return <<setTimestamp(time() - $info['total_cache_uptime']); - - return (new DriverStatistic()) - ->setInfo(sprintf("The Wincache daemon is up since %s.\n For more information see RawData.", $date->format(DATE_RFC2822))) - ->setSize($memInfo['memory_free'] - $memInfo['memory_total']) - ->setData(implode(', ', array_keys($this->itemInstances))) - ->setRawData($memInfo); - } - - /** - * @return bool - */ - protected function driverConnect(): bool - { - return true; - } - - /** - * @param ExtendedCacheItemInterface $item - * @return ?array - */ - protected function driverRead(ExtendedCacheItemInterface $item): ?array - { - $val = wincache_ucache_get($item->getKey(), $suc); - - if ($suc === false || empty($val)) { - return null; - } - - return $val; - } - - /** - * @param ExtendedCacheItemInterface $item - * @return mixed - * @throws PhpfastcacheInvalidArgumentException - * @throws PhpfastcacheLogicException - */ - protected function driverWrite(ExtendedCacheItemInterface $item): bool - { - - return wincache_ucache_set($item->getKey(), $this->driverPreWrap($item), $item->getTtl()); - } - - /** - * @param string $key - * @param string $encodedKey - * @return bool - */ - protected function driverDelete(string $key, string $encodedKey): bool - { - return wincache_ucache_delete($key); - } - - /** - * @return bool - */ - protected function driverClear(): bool - { - return wincache_ucache_clear(); - } -} diff --git a/lib/Phpfastcache/Drivers/Zenddisk/Driver.php b/lib/Phpfastcache/Drivers/Zenddisk/Driver.php index 93a895cf..e0f2ac0e 100644 --- a/lib/Phpfastcache/Drivers/Zenddisk/Driver.php +++ b/lib/Phpfastcache/Drivers/Zenddisk/Driver.php @@ -59,7 +59,6 @@ public function getStats(): DriverStatistic $stat = new DriverStatistic(); $stat->setInfo('[ZendDisk] A void info string') ->setSize(0) - ->setData(implode(', ', array_keys($this->itemInstances))) ->setRawData(false); return $stat; diff --git a/lib/Phpfastcache/Drivers/Zendshm/Driver.php b/lib/Phpfastcache/Drivers/Zendshm/Driver.php index 157c744e..dd274c98 100644 --- a/lib/Phpfastcache/Drivers/Zendshm/Driver.php +++ b/lib/Phpfastcache/Drivers/Zendshm/Driver.php @@ -58,7 +58,6 @@ public function getStats(): DriverStatistic { $stats = (array)zend_shm_cache_info(); return (new DriverStatistic()) - ->setData(implode(', ', array_keys($this->itemInstances))) ->setInfo(sprintf("The Zend memory have %d item(s) in cache.\n For more information see RawData.", $stats['items_total'])) ->setRawData($stats) ->setSize($stats['memory_total']); diff --git a/lib/Phpfastcache/Entities/DriverStatistic.php b/lib/Phpfastcache/Entities/DriverStatistic.php index 26f5b7fe..f9ef069c 100644 --- a/lib/Phpfastcache/Entities/DriverStatistic.php +++ b/lib/Phpfastcache/Entities/DriverStatistic.php @@ -79,25 +79,6 @@ public function setCount(?int $count): static return $this; } - /** - * Return an array of item keys used by this driver instance (deprecated as of v9.2.3, will be removed as of v10) - * @deprecated as of phpfastcache 9.2.3, will be removed as of v10 - */ - public function getData(): string - { - return $this->data; - } - - /** - * @deprecated as of phpfastcache 9.2.3, will be removed as of v10 - */ - public function setData(string $data): static - { - $this->data = ($data ?: ''); - - return $this; - } - /** * Return a bunch of random data provided by the driver. Any type can be provided, usually an array * @return mixed @@ -123,7 +104,6 @@ public function getPublicDesc(): array 'Info' => 'Cache Information', 'Size' => 'Cache Size', 'Count' => 'Cache database/collection count', - 'Data' => 'Cache items keys (Deprecated)', 'RawData' => 'Cache raw data', ]; } diff --git a/lib/Phpfastcache/Drivers/Wincache/Item.php b/lib/Phpfastcache/Event/Event/AbstractItemEvent.php similarity index 50% rename from lib/Phpfastcache/Drivers/Wincache/Item.php rename to lib/Phpfastcache/Event/Event/AbstractItemEvent.php index f490fbe3..63172cb9 100644 --- a/lib/Phpfastcache/Drivers/Wincache/Item.php +++ b/lib/Phpfastcache/Event/Event/AbstractItemEvent.php @@ -14,20 +14,23 @@ declare(strict_types=1); -namespace Phpfastcache\Drivers\Wincache; +namespace Phpfastcache\Event\Event; use Phpfastcache\Core\Item\ExtendedCacheItemInterface; -use Phpfastcache\Core\Item\TaggableCacheItemTrait; -/** - * @deprecated will be removed as of v10 due to the lack of updates to PHP8 as officially stated by PHP: https://www.php.net/manual/en/install.windows.recommended.php - */ -class Item implements ExtendedCacheItemInterface +abstract class AbstractItemEvent extends AbstractStoppableEvent implements EventInterface { - use TaggableCacheItemTrait; + public static function getName(): string + { + return static::EVENT_NAME; + } + + public function __construct(protected ExtendedCacheItemInterface $item) + { + } - protected function getDriverClass(): string + public function getItem(): ExtendedCacheItemInterface { - return Driver::class; + return $this->item; } } diff --git a/lib/Phpfastcache/Event/Event/AbstractItemPoolEvent.php b/lib/Phpfastcache/Event/Event/AbstractItemPoolEvent.php new file mode 100644 index 00000000..9db77be6 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/AbstractItemPoolEvent.php @@ -0,0 +1,36 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; + +abstract class AbstractItemPoolEvent extends AbstractStoppableEvent implements EventInterface +{ + public static function getName(): string + { + return static::EVENT_NAME; + } + + public function __construct(protected ExtendedCacheItemPoolInterface $itemPool) + { + } + + public function getItemPool(): ExtendedCacheItemPoolInterface + { + return $this->itemPool; + } +} diff --git a/lib/Phpfastcache/Event/Event/AbstractStoppableEvent.php b/lib/Phpfastcache/Event/Event/AbstractStoppableEvent.php new file mode 100644 index 00000000..3f5b8b39 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/AbstractStoppableEvent.php @@ -0,0 +1,32 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +abstract class AbstractStoppableEvent implements EventInterface +{ + protected bool $isPropagationStopped = false; + + public function stopPropagation(): void + { + $this->isPropagationStopped = true; + } + + public function isPropagationStopped(): bool + { + return $this->isPropagationStopped; + } +} diff --git a/lib/Phpfastcache/Event/Event/CacheCommitItemEvent.php b/lib/Phpfastcache/Event/Event/CacheCommitItemEvent.php new file mode 100644 index 00000000..f20ac119 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheCommitItemEvent.php @@ -0,0 +1,26 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Event\EventsInterface; + +class CacheCommitItemEvent extends AbstractItemPoolEvent +{ + use CacheItemPoolReferenceParameterEventTrait; + + public const EVENT_NAME = EventsInterface::CACHE_COMMIT_ITEM; +} diff --git a/lib/Phpfastcache/Event/EventInterface.php b/lib/Phpfastcache/Event/Event/CacheDriverCheckedEvent.php similarity index 64% rename from lib/Phpfastcache/Event/EventInterface.php rename to lib/Phpfastcache/Event/Event/CacheDriverCheckedEvent.php index f951e3e5..cdb14767 100644 --- a/lib/Phpfastcache/Event/EventInterface.php +++ b/lib/Phpfastcache/Event/Event/CacheDriverCheckedEvent.php @@ -14,12 +14,11 @@ declare(strict_types=1); -namespace Phpfastcache\Event; +namespace Phpfastcache\Event\Event; -interface EventInterface +use Phpfastcache\Event\EventsInterface; + +class CacheDriverCheckedEvent extends AbstractItemPoolEvent { - /** - * @return array - */ - public static function getEvents(): array; + public const EVENT_NAME = EventsInterface::CACHE_DRIVER_CHECKED; } diff --git a/lib/Phpfastcache/Drivers/Memstatic/Item.php b/lib/Phpfastcache/Event/Event/CacheDriverConnectedEvent.php similarity index 51% rename from lib/Phpfastcache/Drivers/Memstatic/Item.php rename to lib/Phpfastcache/Event/Event/CacheDriverConnectedEvent.php index e4f58328..27a899d1 100644 --- a/lib/Phpfastcache/Drivers/Memstatic/Item.php +++ b/lib/Phpfastcache/Event/Event/CacheDriverConnectedEvent.php @@ -14,20 +14,25 @@ declare(strict_types=1); -namespace Phpfastcache\Drivers\Memstatic; +namespace Phpfastcache\Event\Event; use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; -use Phpfastcache\Event\EventManagerInterface; +use Phpfastcache\Event\EventsInterface; -/** - * @deprecated Memstatic driver has changed its name, it is now called "Memory". - * @see \Phpfastcache\Drivers\Memory\Item - */ -class Item extends \Phpfastcache\Drivers\Memory\Item +class CacheDriverConnectedEvent extends AbstractItemPoolEvent { - public function __construct(ExtendedCacheItemPoolInterface $driver, string $key, EventManagerInterface $em) + public const EVENT_NAME = EventsInterface::CACHE_DRIVER_CONNECTED; + + public function __construct(ExtendedCacheItemPoolInterface $itemPool, protected ?object $driverInstance) + { + parent::__construct($itemPool); + } + + /** + * @return object|null + */ + public function getDriverInstance(): ?object { - trigger_error('Memstatic driver has changed its name, it is now called "Memory"', E_USER_DEPRECATED); - parent::__construct($driver, $key, $em); + return $this->driverInstance; } } diff --git a/lib/Phpfastcache/Event/Event/CacheGetAllItemsEvent.php b/lib/Phpfastcache/Event/Event/CacheGetAllItemsEvent.php new file mode 100644 index 00000000..fc1ae6e9 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheGetAllItemsEvent.php @@ -0,0 +1,26 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Event\EventsInterface; + +class CacheGetAllItemsEvent extends AbstractItemPoolEvent +{ + use CacheItemPoolReferenceParameterEventTrait; + + public const EVENT_NAME = EventsInterface::CACHE_GET_ALL_ITEMS; +} diff --git a/lib/Phpfastcache/Event/Event/CacheGetItemEvent.php b/lib/Phpfastcache/Event/Event/CacheGetItemEvent.php new file mode 100644 index 00000000..dab72297 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheGetItemEvent.php @@ -0,0 +1,27 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Core\Item\ExtendedCacheItemInterface; +use Phpfastcache\Event\EventsInterface; + +class CacheGetItemEvent extends AbstractItemPoolEvent +{ + use CacheItemEventTrait; + + public const EVENT_NAME = EventsInterface::CACHE_GET_ITEM; +} diff --git a/lib/Phpfastcache/Event/Event/CacheGetItemInSlamBatchItemPoolEvent.php b/lib/Phpfastcache/Event/Event/CacheGetItemInSlamBatchItemPoolEvent.php new file mode 100644 index 00000000..0bb7fdee --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheGetItemInSlamBatchItemPoolEvent.php @@ -0,0 +1,47 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; +use Phpfastcache\Entities\ItemBatch; +use Phpfastcache\Event\EventsInterface; + +class CacheGetItemInSlamBatchItemPoolEvent extends AbstractItemPoolEvent +{ + public const EVENT_NAME = EventsInterface::CACHE_GET_ITEM_IN_SLAM_BATCH; + + public function __construct(ExtendedCacheItemPoolInterface $itemPool, protected ItemBatch $itemBatch, protected float|int $cacheSlamsSpendSeconds) + { + parent::__construct($itemPool); + } + + /** + * @return ItemBatch + */ + public function getItemBatch(): ItemBatch + { + return $this->itemBatch; + } + + /** + * @return float|int + */ + public function getCacheSlamsSpendSeconds(): float|int + { + return $this->cacheSlamsSpendSeconds; + } +} diff --git a/lib/Phpfastcache/Event/Event/CacheItemEventTrait.php b/lib/Phpfastcache/Event/Event/CacheItemEventTrait.php new file mode 100644 index 00000000..79ae689e --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheItemEventTrait.php @@ -0,0 +1,33 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Core\Item\ExtendedCacheItemInterface; +use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; +use Psr\Cache\CacheItemInterface; + +trait CacheItemEventTrait +{ + public function __construct(protected ExtendedCacheItemPoolInterface $itemPool, protected ExtendedCacheItemInterface|CacheItemInterface $cacheItem) + { + } + + public function getCacheItem(): ExtendedCacheItemInterface|CacheItemInterface + { + return $this->cacheItem; + } +} diff --git a/lib/Phpfastcache/Event/Event/CacheItemExpireAfterEvent.php b/lib/Phpfastcache/Event/Event/CacheItemExpireAfterEvent.php new file mode 100644 index 00000000..1c113595 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheItemExpireAfterEvent.php @@ -0,0 +1,38 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Core\Item\ExtendedCacheItemInterface; +use Phpfastcache\Event\EventsInterface; + +class CacheItemExpireAfterEvent extends AbstractItemEvent +{ + public const EVENT_NAME = EventsInterface::CACHE_ITEM_EXPIRE_AFTER; + + public function __construct(ExtendedCacheItemInterface $item, protected int|\DateInterval|null $expireAfter) + { + parent::__construct($item); + } + + /** + * @return int|\DateInterval|null + */ + public function getExpireAfter(): int|\DateInterval|null + { + return $this->expireAfter; + } +} diff --git a/lib/Phpfastcache/Event/Event/CacheItemExpireAtEvent.php b/lib/Phpfastcache/Event/Event/CacheItemExpireAtEvent.php new file mode 100644 index 00000000..c284dba0 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheItemExpireAtEvent.php @@ -0,0 +1,39 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Core\Item\ExtendedCacheItemInterface; +use Phpfastcache\Event\EventReferenceParameter; +use Phpfastcache\Event\EventsInterface; + +class CacheItemExpireAtEvent extends AbstractItemEvent +{ + public const EVENT_NAME = EventsInterface::CACHE_ITEM_EXPIRE_AT; + + public function __construct(ExtendedCacheItemInterface $item, protected \DateTimeInterface $expireAt) + { + parent::__construct($item); + } + + /** + * @return \DateTimeInterface + */ + public function getExpireAt(): \DateTimeInterface + { + return $this->expireAt; + } +} diff --git a/lib/Phpfastcache/Event/Event/CacheItemPoolEventClearItems.php b/lib/Phpfastcache/Event/Event/CacheItemPoolEventClearItems.php new file mode 100644 index 00000000..09c7a6f3 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheItemPoolEventClearItems.php @@ -0,0 +1,26 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Event\EventsInterface; + +class CacheItemPoolEventClearItems extends AbstractItemPoolEvent +{ + use CacheItemsEventTrait; + + public const EVENT_NAME = EventsInterface::CACHE_CLEAR_ITEMS; +} diff --git a/lib/Phpfastcache/Event/Event/CacheItemPoolEventClusterBuilt.php b/lib/Phpfastcache/Event/Event/CacheItemPoolEventClusterBuilt.php new file mode 100644 index 00000000..e9382625 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheItemPoolEventClusterBuilt.php @@ -0,0 +1,39 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Cluster\AggregatorInterface; +use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; +use Phpfastcache\Event\EventsInterface; + +class CacheItemPoolEventClusterBuilt extends AbstractItemPoolEvent +{ + public const EVENT_NAME = EventsInterface::CACHE_CLUSTER_BUILT; + + public function __construct(ExtendedCacheItemPoolInterface $itemPool, protected AggregatorInterface $clusterAggregator) + { + parent::__construct($itemPool); + } + + /** + * @return AggregatorInterface + */ + public function getClusterAggregator(): AggregatorInterface + { + return $this->clusterAggregator; + } +} diff --git a/lib/Phpfastcache/Event/Event/CacheItemPoolEventDeleteItem.php b/lib/Phpfastcache/Event/Event/CacheItemPoolEventDeleteItem.php new file mode 100644 index 00000000..497c0828 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheItemPoolEventDeleteItem.php @@ -0,0 +1,26 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Event\EventsInterface; + +class CacheItemPoolEventDeleteItem extends AbstractItemPoolEvent +{ + use CacheItemEventTrait; + + public const EVENT_NAME = EventsInterface::CACHE_DELETE_ITEM; +} diff --git a/lib/Phpfastcache/Event/Event/CacheItemPoolEventDeleteItems.php b/lib/Phpfastcache/Event/Event/CacheItemPoolEventDeleteItems.php new file mode 100644 index 00000000..599eb5d4 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheItemPoolEventDeleteItems.php @@ -0,0 +1,26 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Event\EventsInterface; + +class CacheItemPoolEventDeleteItems extends AbstractItemPoolEvent +{ + use CacheItemsEventTrait; + + public const EVENT_NAME = EventsInterface::CACHE_DELETE_ITEMS; +} diff --git a/lib/Phpfastcache/Event/Event/CacheItemPoolEventGetItems.php b/lib/Phpfastcache/Event/Event/CacheItemPoolEventGetItems.php new file mode 100644 index 00000000..5e374a8b --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheItemPoolEventGetItems.php @@ -0,0 +1,28 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Core\Item\ExtendedCacheItemInterface; +use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; +use Phpfastcache\Event\EventsInterface; + +class CacheItemPoolEventGetItems extends AbstractItemPoolEvent +{ + use CacheItemsEventTrait; + + public const EVENT_NAME = EventsInterface::CACHE_GET_ITEMS; +} diff --git a/lib/Phpfastcache/Event/Event/CacheItemPoolEventSaveItem.php b/lib/Phpfastcache/Event/Event/CacheItemPoolEventSaveItem.php new file mode 100644 index 00000000..6170f8f4 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheItemPoolEventSaveItem.php @@ -0,0 +1,26 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Event\EventsInterface; + +class CacheItemPoolEventSaveItem extends AbstractItemPoolEvent +{ + use CacheItemEventTrait; + + public const EVENT_NAME = EventsInterface::CACHE_SAVE_ITEM; +} diff --git a/lib/Phpfastcache/Event/Event/CacheItemPoolReferenceParameterEventTrait.php b/lib/Phpfastcache/Event/Event/CacheItemPoolReferenceParameterEventTrait.php new file mode 100644 index 00000000..14b5b57f --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheItemPoolReferenceParameterEventTrait.php @@ -0,0 +1,35 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; +use Phpfastcache\Event\EventReferenceParameter; + +/** + * @suppressWarnings(PHPMD.LongClassName) + */ +trait CacheItemPoolReferenceParameterEventTrait +{ + public function __construct(protected ExtendedCacheItemPoolInterface $itemPool, protected EventReferenceParameter $eventReferenceParameter) + { + } + + public function getEventReferenceParameter(): EventReferenceParameter + { + return $this->eventReferenceParameter; + } +} diff --git a/lib/Phpfastcache/Event/Event/CacheItemReferenceParameterEventTrait.php b/lib/Phpfastcache/Event/Event/CacheItemReferenceParameterEventTrait.php new file mode 100644 index 00000000..12d41287 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheItemReferenceParameterEventTrait.php @@ -0,0 +1,32 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Core\Item\ExtendedCacheItemInterface; +use Phpfastcache\Event\EventReferenceParameter; + +trait CacheItemReferenceParameterEventTrait +{ + public function __construct(protected ExtendedCacheItemInterface $item, protected EventReferenceParameter $eventReferenceParameter) + { + } + + public function getEventReferenceParameter(): EventReferenceParameter + { + return $this->eventReferenceParameter; + } +} diff --git a/lib/Phpfastcache/Event/Event/CacheItemSetEvent.php b/lib/Phpfastcache/Event/Event/CacheItemSetEvent.php new file mode 100644 index 00000000..539235ee --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheItemSetEvent.php @@ -0,0 +1,26 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Event\EventsInterface; + +class CacheItemSetEvent extends AbstractItemEvent +{ + use CacheItemReferenceParameterEventTrait; + + public const EVENT_NAME = EventsInterface::CACHE_ITEM_SET; +} diff --git a/lib/Phpfastcache/Event/Event/CacheItemsEventTrait.php b/lib/Phpfastcache/Event/Event/CacheItemsEventTrait.php new file mode 100644 index 00000000..67fbdebd --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheItemsEventTrait.php @@ -0,0 +1,40 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Core\Item\ExtendedCacheItemInterface; +use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; +use Psr\Cache\CacheItemInterface; + +trait CacheItemsEventTrait +{ + /** + * @param ExtendedCacheItemPoolInterface $itemPool + * @param array $cacheItems + */ + public function __construct(protected ExtendedCacheItemPoolInterface $itemPool, protected array $cacheItems) + { + } + + /** + * @return array + */ + public function getCacheItems(): array + { + return $this->cacheItems; + } +} diff --git a/lib/Phpfastcache/Event/Event/CacheReplicationRandomPoolChosenItemPoolEvent.php b/lib/Phpfastcache/Event/Event/CacheReplicationRandomPoolChosenItemPoolEvent.php new file mode 100644 index 00000000..518a5b76 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheReplicationRandomPoolChosenItemPoolEvent.php @@ -0,0 +1,41 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; +use Phpfastcache\Event\EventsInterface; + +/** + * @suppressWarnings(PHPMD.LongClassName) + */ +class CacheReplicationRandomPoolChosenItemPoolEvent extends AbstractItemPoolEvent +{ + public const EVENT_NAME = EventsInterface::CACHE_REPLICATION_RANDOM_POOL_CHOSEN; + + public function __construct(ExtendedCacheItemPoolInterface $itemPool, protected ExtendedCacheItemPoolInterface $randomPool) + { + parent::__construct($itemPool); + } + + /** + * @return ExtendedCacheItemPoolInterface + */ + public function getRandomPool(): ExtendedCacheItemPoolInterface + { + return $this->randomPool; + } +} diff --git a/lib/Phpfastcache/Event/Event/CacheReplicationSlaveFallbackItemPoolEvent.php b/lib/Phpfastcache/Event/Event/CacheReplicationSlaveFallbackItemPoolEvent.php new file mode 100644 index 00000000..41abb528 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheReplicationSlaveFallbackItemPoolEvent.php @@ -0,0 +1,41 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; +use Phpfastcache\Event\EventsInterface; + +/** + * @suppressWarnings(PHPMD.LongClassName) + */ +class CacheReplicationSlaveFallbackItemPoolEvent extends AbstractItemPoolEvent +{ + public const EVENT_NAME = EventsInterface::CACHE_REPLICATION_SLAVE_FALLBACK; + + public function __construct(ExtendedCacheItemPoolInterface $itemPool, protected string $methodCaller) + { + parent::__construct($itemPool); + } + + /** + * @return string + */ + public function getMethodCaller(): string + { + return $this->methodCaller; + } +} diff --git a/lib/Phpfastcache/Event/Event/CacheSaveDeferredItemItemPoolEvent.php b/lib/Phpfastcache/Event/Event/CacheSaveDeferredItemItemPoolEvent.php new file mode 100644 index 00000000..de224801 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheSaveDeferredItemItemPoolEvent.php @@ -0,0 +1,26 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Event\EventsInterface; + +class CacheSaveDeferredItemItemPoolEvent extends AbstractItemPoolEvent +{ + use CacheItemEventTrait; + + public const EVENT_NAME = EventsInterface::CACHE_SAVE_DEFERRED_ITEM; +} diff --git a/lib/Phpfastcache/Event/Event/CacheSaveMultipleItemsItemPoolEvent.php b/lib/Phpfastcache/Event/Event/CacheSaveMultipleItemsItemPoolEvent.php new file mode 100644 index 00000000..0da64e8b --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheSaveMultipleItemsItemPoolEvent.php @@ -0,0 +1,26 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Event\EventsInterface; + +class CacheSaveMultipleItemsItemPoolEvent extends AbstractItemPoolEvent +{ + use CacheItemPoolReferenceParameterEventTrait; + + public const EVENT_NAME = EventsInterface::CACHE_SAVE_MULTIPLE_ITEMS; +} diff --git a/lib/Phpfastcache/Event/Event/CacheWriteFileOnDiskItemPoolEvent.php b/lib/Phpfastcache/Event/Event/CacheWriteFileOnDiskItemPoolEvent.php new file mode 100644 index 00000000..2e6dbdb6 --- /dev/null +++ b/lib/Phpfastcache/Event/Event/CacheWriteFileOnDiskItemPoolEvent.php @@ -0,0 +1,38 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; +use Phpfastcache\Event\EventsInterface; + +class CacheWriteFileOnDiskItemPoolEvent extends AbstractItemPoolEvent +{ + public const EVENT_NAME = EventsInterface::CACHE_WRITE_FILE_ON_DISK; + + public function __construct(ExtendedCacheItemPoolInterface $itemPool, protected string $file) + { + parent::__construct($itemPool); + } + + /** + * @return string + */ + public function getFile(): string + { + return $this->file; + } +} diff --git a/lib/Phpfastcache/Event/Event/EventInterface.php b/lib/Phpfastcache/Event/Event/EventInterface.php new file mode 100644 index 00000000..82a3084d --- /dev/null +++ b/lib/Phpfastcache/Event/Event/EventInterface.php @@ -0,0 +1,29 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event\Event; + +use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; +use Psr\EventDispatcher\StoppableEventInterface; + +interface EventInterface extends StoppableEventInterface +{ + public const EVENT_NAME = ''; + + public static function getName(): string; + + public function stopPropagation(): void; +} diff --git a/lib/Phpfastcache/Event/EventManagerDispatcherInterface.php b/lib/Phpfastcache/Event/EventManagerDispatcherInterface.php index 90975bf4..7391ac2d 100644 --- a/lib/Phpfastcache/Event/EventManagerDispatcherInterface.php +++ b/lib/Phpfastcache/Event/EventManagerDispatcherInterface.php @@ -28,10 +28,4 @@ public function getEventManager(): EventManagerInterface; * @return mixed */ public function setEventManager(EventManagerInterface $eventManager): static; - - /** - * @return bool - * @deprecated Will be removed in v10 - */ - public function hasEventManager(): bool; } diff --git a/lib/Phpfastcache/Event/EventManagerDispatcherTrait.php b/lib/Phpfastcache/Event/EventManagerDispatcherTrait.php index e98c2d71..b3851690 100644 --- a/lib/Phpfastcache/Event/EventManagerDispatcherTrait.php +++ b/lib/Phpfastcache/Event/EventManagerDispatcherTrait.php @@ -39,13 +39,4 @@ public function setEventManager(EventManagerInterface $em): static $this->eventManager = $em; return $this; } - - /** - * @deprecated Will be removed in v10 - * @return bool - */ - public function hasEventManager(): bool - { - return isset($this->eventManager); - } } diff --git a/lib/Phpfastcache/Event/EventManagerInterface.php b/lib/Phpfastcache/Event/EventManagerInterface.php index 7dcfb6aa..5773377b 100644 --- a/lib/Phpfastcache/Event/EventManagerInterface.php +++ b/lib/Phpfastcache/Event/EventManagerInterface.php @@ -20,39 +20,13 @@ use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; use Phpfastcache\Exceptions\PhpfastcacheEventManagerException; use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException; +use Psr\EventDispatcher\EventDispatcherInterface; +use Psr\EventDispatcher\ListenerProviderInterface; /** - * == ItemPool Events == - * @method Void onCacheGetItem(Callable $callable, ?string $callbackName = null) - * @method Void onCacheGetItems(Callable $callable, ?string $callbackName = null) - * @method Void onCacheDeleteItem(Callable $callable, ?string $callbackName = null) - * @method Void onCacheSaveItem(Callable $callable, ?string $callbackName = null) - * @method Void onCacheSaveMultipleItems(Callable $callable, ?string $callbackName = null) - * @method Void onCacheSaveDeferredItem(Callable $callable, ?string $callbackName = null) - * @method Void onCacheCommitItem(Callable $callable, ?string $callbackName = null) - * @method Void onCacheClearItem(Callable $callable, ?string $callbackName = null) - * @method Void onCacheWriteFileOnDisk(Callable $callable, ?string $callbackName = null) - * @method Void onCacheGetItemInSlamBatch(Callable $callable, ?string $callbackName = null) - * - * == ItemPool Events (Cluster) == - * @method Void onCacheReplicationSlaveFallback(Callable $callable, ?string $callbackName = null) - * @method Void onCacheReplicationRandomPoolChosen(Callable $callable, ?string $callbackName = null) - * @method Void onCacheClusterBuilt(Callable $callable, ?string $callbackName = null) - * - * == Item Events == - * @method Void onCacheItemSet(Callable $callable, ?string $callbackName = null) - * @method Void onCacheItemExpireAt(Callable $callable, ?string $callbackName = null) - * @method Void onCacheItemExpireAfter(Callable $callable, ?string $callbackName = null) - * - * == Driver-specific events == - * @method Void onArangodbConnection(Callable $callable, ?string $callbackName = null) - * @method Void onArangodbCollectionParams(Callable $callable, ?string $callbackName = null) - * @method Void onCouchdbCreateOptions(Callable $callable, ?string $callbackName = null) - * @method Void onDynamodbCreateTable(Callable $callable, ?string $callbackName = null) - * @method Void onSolrBuildEndpoint(Callable $callable, ?string $callbackName = null) - * @method Void onFirestoreClientOptions(Callable $callable, ?string $callbackName = null) + * @see EventsInterface for the list of available events. */ -interface EventManagerInterface +interface EventManagerInterface extends EventDispatcherInterface, ListenerProviderInterface { /** * @return self @@ -65,12 +39,6 @@ public static function getInstance(): EventManagerInterface; */ public static function setInstance(EventManagerInterface $eventManagerInstance): void; - /** - * @param string $eventName - * @param array $args - */ - public function dispatch(string $eventName, ...$args): void; - /** * @param string $name * @param array $arguments @@ -83,13 +51,13 @@ public function __call(string $name, array $arguments): void; * @param callable $callback * @param string $callbackName */ - public function onEveryEvents(callable $callback, string $callbackName): void; + public function addGlobalListener(callable $callback, string $callbackName): void; /** * @param string[]|string $events * @param callable $callback */ - public function on(array|string $events, callable $callback): void; + public function addListener(array|string $events, callable $callback): void; /** * @param string $eventName diff --git a/lib/Phpfastcache/Event/Events.php b/lib/Phpfastcache/Event/Events.php new file mode 100644 index 00000000..d1c8dd40 --- /dev/null +++ b/lib/Phpfastcache/Event/Events.php @@ -0,0 +1,29 @@ + + * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors + */ + +declare(strict_types=1); + +namespace Phpfastcache\Event; + +use Phpfastcache\Helper\UninstanciableObjectTrait; + +class Events implements EventsInterface +{ + use UninstanciableObjectTrait; + + public static function getEvents(): array + { + return (new \ReflectionClass(static::class))->getConstants(); + } +} diff --git a/lib/Phpfastcache/Event/Event.php b/lib/Phpfastcache/Event/EventsInterface.php similarity index 83% rename from lib/Phpfastcache/Event/Event.php rename to lib/Phpfastcache/Event/EventsInterface.php index 1225a5b6..f3b67de4 100644 --- a/lib/Phpfastcache/Event/Event.php +++ b/lib/Phpfastcache/Event/EventsInterface.php @@ -16,12 +16,8 @@ namespace Phpfastcache\Event; -use Phpfastcache\Helper\UninstanciableObjectTrait; - -class Event implements EventInterface +interface EventsInterface { - use UninstanciableObjectTrait; - public const CACHE_GET_ITEM = 'CacheGetItem'; public const CACHE_GET_ITEMS = 'CacheGetItems'; public const CACHE_DELETE_ITEM = 'CacheDeleteItem'; @@ -30,7 +26,7 @@ class Event implements EventInterface public const CACHE_SAVE_MULTIPLE_ITEMS = 'CacheSaveMultipleItems'; public const CACHE_SAVE_DEFERRED_ITEM = 'CacheSaveDeferredItem'; public const CACHE_COMMIT_ITEM = 'CacheCommitItem'; - public const CACHE_CLEAR_ITEM = 'CacheClearItem'; + public const CACHE_CLEAR_ITEMS = 'CacheClearItems'; public const CACHE_WRITE_FILE_ON_DISK = 'CacheWriteFileOnDisk'; public const CACHE_GET_ITEM_IN_SLAM_BATCH = 'CacheGetItemInSlamBatch'; public const CACHE_REPLICATION_SLAVE_FALLBACK = 'CacheReplicationSlaveFallback'; @@ -43,8 +39,8 @@ class Event implements EventInterface public const CACHE_DRIVER_CHECKED = 'CacheDriverChecked'; public const CACHE_DRIVER_CONNECTED = 'CacheDriverConnected'; - public static function getEvents(): array - { - return (new \ReflectionClass(static::class))->getConstants(); - } + /** + * @return array + */ + public static function getEvents(): array; } diff --git a/lib/Phpfastcache/EventManager.php b/lib/Phpfastcache/EventManager.php index 9c646575..cbc041d5 100644 --- a/lib/Phpfastcache/EventManager.php +++ b/lib/Phpfastcache/EventManager.php @@ -17,6 +17,7 @@ namespace Phpfastcache; use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; +use Phpfastcache\Event\Event\EventInterface; use Phpfastcache\Event\EventManagerInterface; use Phpfastcache\Exceptions\PhpfastcacheEventManagerException; use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException; @@ -35,7 +36,7 @@ class EventManager implements EventManagerInterface protected ?ExtendedCacheItemPoolInterface $itemPoolContext = null; /** @var array> */ - protected array $events = [ + protected array $listeners = [ self::ON_EVERY_EVENT => [] ]; @@ -56,25 +57,39 @@ public static function setInstance(EventManagerInterface $eventManagerInstance): self::$instance = $eventManagerInstance; } - public function dispatch(string $eventName, ...$args): void + /** + * @param object $event + * @return object + * @throws PhpfastcacheInvalidArgumentException + */ + public function dispatch(object $event) { - /** - * Replace array_key_exists by isset - * due to performance issue on huge - * loop dispatching operations - */ - if (isset($this->events[$eventName]) && $eventName !== self::ON_EVERY_EVENT) { - $loopArgs = array_merge($args, [$eventName]); - foreach ($this->events[$eventName] as $event) { - /** - * @todo V10: BC Break: Put eventName as first parameter (like self::ON_EVERY_EVENT) - */ - $event(...$loopArgs); + if ($event instanceof EventInterface) { + $eventName = $event::getName(); + + if (isset($this->listeners[$eventName]) && $eventName !== self::ON_EVERY_EVENT) { + foreach ($this->listeners[$eventName] as $listener) { + if ($event->isPropagationStopped()) { + return $event; + } + $listener($event); + } } + foreach ($this->listeners[self::ON_EVERY_EVENT] as $listener) { + if ($event->isPropagationStopped()) { + return $event; + } + $listener($event); + } + return $event; } - foreach ($this->events[self::ON_EVERY_EVENT] as $event) { - $event($eventName, ...$args); - } + + throw new PhpfastcacheInvalidArgumentException( + sprintf( + 'Method EventManager::dispatch() only accept %s events.', + EventInterface::class + ) + ); } /** @@ -85,15 +100,18 @@ public function dispatch(string $eventName, ...$args): void public function __call(string $name, array $arguments): void { if (\str_starts_with($name, 'on')) { - $name = \substr($name, 2); - if (\is_callable($arguments[0])) { - if (isset($arguments[1]) && \is_string($arguments[0])) { - $this->events[$name][$arguments[1]] = $arguments[0]; - } else { - $this->events[$name][] = $arguments[0]; - } + trigger_error( + sprintf( + 'Method "%s()" is deprecated, please use method "%s()" instead. See the migration guide if you seek for detailed help.', + $name, + $name === 'onEveryEvents' ? 'addGlobalListener' : 'addListener' + ), + E_USER_DEPRECATED + ); + if ($name === 'onEveryEvents') { + $this->addGlobalListener($arguments[0], $arguments[1] ?? spl_object_hash($arguments[0])); } else { - throw new PhpfastcacheInvalidArgumentException(\sprintf('Expected Callable, got "%s"', \gettype($arguments[0]))); + $this->addListener(\substr($name, 2), $arguments[0]); } } else { throw new PhpfastcacheEventManagerException('An event must start with "on" such as "onCacheGetItem"'); @@ -105,29 +123,34 @@ public function __call(string $name, array $arguments): void * @param string $callbackName * @throws PhpfastcacheEventManagerException */ - public function onEveryEvents(callable $callback, string $callbackName): void + public function addGlobalListener(callable $callback, string $callbackName): void { - if ($callbackName === '') { - throw new PhpfastcacheEventManagerException('Callbackname cannot be empty'); + if (trim($callbackName) === '') { + throw new PhpfastcacheEventManagerException('Parameter $callbackName cannot be empty'); } - $this->events[self::ON_EVERY_EVENT][$callbackName] = $callback; + $this->listeners[self::ON_EVERY_EVENT][$callbackName] = $callback; } /** * @throws PhpfastcacheEventManagerException + * @throws PhpfastcacheInvalidArgumentException */ - public function on(array|string $events, callable $callback): void + public function addListener(array|string $events, callable|string $callback): void { if (is_string($events)) { $events = [$events]; } + + if (!is_callable($callback)) { + throw new PhpfastcacheInvalidArgumentException(\sprintf('Argument $callback is not callable.')); + } foreach ($events as $event) { if (!\preg_match('#^([a-zA-Z])*$#', $event)) { throw new PhpfastcacheEventManagerException(\sprintf('Invalid event name "%s"', $event)); } - $this->{'on' . \ucfirst($event)}($callback); + $this->listeners[$event][] = $callback; } } @@ -138,8 +161,8 @@ public function on(array|string $events, callable $callback): void */ public function unbindEventCallback(string $eventName, string $callbackName): bool { - $return = isset($this->events[$eventName][$callbackName]); - unset($this->events[$eventName][$callbackName]); + $return = isset($this->listeners[$eventName][$callbackName]); + unset($this->listeners[$eventName][$callbackName]); return $return; } @@ -149,7 +172,7 @@ public function unbindEventCallback(string $eventName, string $callbackName): bo */ public function unbindAllEventCallbacks(): bool { - $this->events = [ + $this->listeners = [ self::ON_EVERY_EVENT => [] ]; @@ -184,14 +207,23 @@ public function setItemPoolContext(ExtendedCacheItemPoolInterface $pool): EventM } $this->itemPoolContext = $pool; - $this->onEveryEvents(function (string $eventName, ...$args) { - EventManager::getInstance()->dispatch($eventName, ...$args); + $this->addGlobalListener(static function (EventInterface $event) { + self::getInstance()->dispatch($event); }, 'Scoped' . $pool->getDriverName() . spl_object_hash($this)); return $this; } -} -// phpcs:disable -\class_alias(EventManager::class, PhpfastcacheEventManager::class); // @phpstan-ignore-line -// phpcs:enable + /** + * @param object $event + * @return array + */ + public function getListenersForEvent(object $event): iterable + { + if ($event instanceof EventInterface) { + return $this->listeners[$event::getName()] ?? []; + } + + return []; + } +} diff --git a/lib/Phpfastcache/Helper/CacheConditionalHelper.php b/lib/Phpfastcache/Helper/CacheConditionalHelper.php deleted file mode 100644 index 2199fc4e..00000000 --- a/lib/Phpfastcache/Helper/CacheConditionalHelper.php +++ /dev/null @@ -1,44 +0,0 @@ - - * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors - */ - -declare(strict_types=1); - -namespace Phpfastcache\Helper; - -use Phpfastcache\CacheContract; -use Psr\Cache\CacheItemPoolInterface; - -/** - * @deprecated Use \Phpfastcache\CacheContract instead - */ -class CacheConditionalHelper extends CacheContract -{ - /** - * CacheConditionalHelper constructor. - * @param CacheItemPoolInterface $cacheInstance - */ - public function __construct(CacheItemPoolInterface $cacheInstance) - { - \trigger_error( - \sprintf( - 'Class "%s" is deprecated, use "%s" class instead. See the documentation about this change here: %s', - self::class, - parent::class, - 'https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV9%CB%96%5D-Cache-contract' - ), - E_USER_DEPRECATED - ); - parent::__construct($cacheInstance); - } -} diff --git a/tests/cases/EventManager.test.php b/tests/cases/EventManager.test.php index cb632a2c..8742e0d0 100644 --- a/tests/cases/EventManager.test.php +++ b/tests/cases/EventManager.test.php @@ -19,6 +19,7 @@ use Phpfastcache\EventManager; use Phpfastcache\Exceptions\PhpfastcacheInvalidTypeException; use Phpfastcache\Tests\Helper\TestHelper; +use Phpfastcache\Event\Events; chdir(__DIR__); require_once __DIR__ . '/../../vendor/autoload.php'; @@ -28,15 +29,15 @@ $cacheInstance = CacheManager::getInstance($defaultDriver); $eventInstance = $cacheInstance->getEventManager(); $testHelper->debugEvents($eventInstance); -$eventInstance->onCacheSaveItem(static function (ExtendedCacheItemPoolInterface $itemPool, ExtendedCacheItemInterface $item) { - if ($item->_getData() === 1000) { - $item->increment(337); +$eventInstance->addListener(Events::CACHE_SAVE_ITEM, static function (\Phpfastcache\Event\Event\CacheItemPoolEventSaveItem $event) { + if ($event->getCacheItem()->_getData() === 1000) { + $event->getCacheItem()->increment(337); } }); -$eventInstance->onCacheItemSet(static function (ExtendedCacheItemInterface $item, EventReferenceParameter $eventReferenceParameter) use ($testHelper) { +$eventInstance->addListener(Events::CACHE_ITEM_SET, static function (\Phpfastcache\Event\Event\CacheItemSetEvent $event) use ($testHelper) { try{ - $eventReferenceParameter->setParameterValue(1000); + $event->getEventReferenceParameter()->setParameterValue(1000); $testHelper->assertPass('The event reference parameter accepted a value type change'); } catch(PhpfastcacheInvalidTypeException){ $testHelper->assertFail('The event reference parameter denied a value type change'); @@ -60,15 +61,15 @@ $eventInstance->unbindAllEventCallbacks(); $testHelper->debugEvents($eventInstance); -$eventInstance->onCacheSaveMultipleItems(static function (ExtendedCacheItemPoolInterface $itemPool, EventReferenceParameter $eventReferenceParameter) use ($testHelper) { - $parameterValue = $eventReferenceParameter->getParameterValue(); +$eventInstance->addListener(Events::CACHE_SAVE_MULTIPLE_ITEMS, static function (\Phpfastcache\Event\Event\CacheSaveMultipleItemsItemPoolEvent $event) use ($testHelper) { + $parameterValue = $event->getEventReferenceParameter()->getParameterValue(); try{ - $eventReferenceParameter->setParameterValue(null); + $event->getEventReferenceParameter()->setParameterValue(null); $testHelper->assertFail('The event reference parameter accepted a value type change'); } catch(PhpfastcacheInvalidTypeException){ $testHelper->assertPass('The event reference parameter denied a value type change'); - $eventReferenceParameter->setParameterValue([]); + $event->getEventReferenceParameter()->setParameterValue([]); } if (is_array($parameterValue) && count($parameterValue) === 2) { diff --git a/tests/cases/EventManagerScoped.test.php b/tests/cases/EventManagerScoped.test.php index 61efb9e9..93f499eb 100644 --- a/tests/cases/EventManagerScoped.test.php +++ b/tests/cases/EventManagerScoped.test.php @@ -36,8 +36,8 @@ $filesGetItemEventManagerCount = 0; $redisGetItemEventManagerCount = 0; -EventManager::getInstance()->onEveryEvents(static function (string $eventName) use ($testHelper, &$globalEveryEventsEvents) { - $testHelper->printInfoText(sprintf('[Global] Global "onEveryEvents" has been called for "%s"', $eventName)); +EventManager::getInstance()->addGlobalListener(static function (string $eventName) use ($testHelper, &$globalEveryEventsEvents) { + $testHelper->printInfoText(sprintf('[Global] Global "addGlobalListener" has been called for "%s"', $eventName)); $globalEveryEventsEvents[$eventName] = ($globalEveryEventsEvents[$eventName] ?? 0) + 1; }, 'GlobalEveryEvent'); @@ -46,8 +46,8 @@ $globalGetItemEventManagerCount++; }); -$filesCacheInstance->getEventManager()->onEveryEvents(static function (string $eventName) use ($testHelper, &$filesEveryEventsEventEvents) { - $testHelper->printInfoText(sprintf('[Files] Scoped "onEveryEvents" has been called for "%s"', $eventName)); +$filesCacheInstance->getEventManager()->addGlobalListener(static function (string $eventName) use ($testHelper, &$filesEveryEventsEventEvents) { + $testHelper->printInfoText(sprintf('[Files] Scoped "addGlobalListener" has been called for "%s"', $eventName)); $filesEveryEventsEventEvents[$eventName] = ($filesEveryEventsEventEvents[$eventName] ?? 0) + 1; }, 'GlobalEveryEvent'); @@ -59,8 +59,8 @@ } }); -$redisCacheInstance->getEventManager()->onEveryEvents(static function (string $eventName) use ($testHelper, &$redisEveryEventsEventEvents) { - $testHelper->printInfoText(sprintf('[Redis] Scoped "onEveryEvents" has been called for "%s"', $eventName)); +$redisCacheInstance->getEventManager()->addGlobalListener(static function (string $eventName) use ($testHelper, &$redisEveryEventsEventEvents) { + $testHelper->printInfoText(sprintf('[Redis] Scoped "addGlobalListener" has been called for "%s"', $eventName)); $redisEveryEventsEventEvents[$eventName] = ($redisEveryEventsEventEvents[$eventName] ?? 0) + 1; }, 'GlobalEveryEvent'); diff --git a/tests/cases/GetAllItems.test.php b/tests/cases/GetAllItems.test.php index 239714ee..6f9ffc3c 100644 --- a/tests/cases/GetAllItems.test.php +++ b/tests/cases/GetAllItems.test.php @@ -13,7 +13,7 @@ */ use Phpfastcache\CacheManager; -use Phpfastcache\Event\Event; +use Phpfastcache\Event\Events; use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException; use Phpfastcache\Exceptions\PhpfastcacheDriverConnectException; use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException; @@ -32,7 +32,7 @@ /** * https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV5%CB%96%5D-Fetching-all-keys */ -EventManager::getInstance()->on([Event::CACHE_GET_ALL_ITEMS], static function(ExtendedCacheItemPoolInterface $driver, EventReferenceParameter $referenceParameter) use ($testHelper, &$eventFlag){ +EventManager::getInstance()->addListener([Events::CACHE_GET_ALL_ITEMS], static function(ExtendedCacheItemPoolInterface $driver, EventReferenceParameter $referenceParameter) use ($testHelper, &$eventFlag){ $callback = $referenceParameter->getParameterValue(); $referenceParameter->setParameterValue(function(string $pattern) use ($callback, &$eventFlag, $testHelper) { $eventFlag = true; From df08c4e9bccd1b3a4725e8fad407bfaa1a71e27d Mon Sep 17 00:00:00 2001 From: Georges Date: Wed, 17 Jan 2024 00:34:18 +0100 Subject: [PATCH 3/6] Fixed tests --- tests/cases/AtomicOperations.test.php | 2 +- tests/cases/CacheSlamsProtection.test.php | 7 ++-- .../ClusterMasterSlaveReplication.test.php | 7 ++-- tests/cases/EventManagerScoped.test.php | 32 +++++++++---------- tests/cases/GetAllItems.test.php | 6 ++-- tests/cases/Memory.test.php | 2 +- tests/cases/Wincache.test.php | 28 ---------------- 7 files changed, 28 insertions(+), 56 deletions(-) delete mode 100644 tests/cases/Wincache.test.php diff --git a/tests/cases/AtomicOperations.test.php b/tests/cases/AtomicOperations.test.php index cf9dcdc4..9771b7f9 100644 --- a/tests/cases/AtomicOperations.test.php +++ b/tests/cases/AtomicOperations.test.php @@ -19,7 +19,7 @@ require_once __DIR__ . '/../../vendor/autoload.php'; require_once __DIR__ . '/../mock/Autoload.php'; $testHelper = new TestHelper('Atomic Operations'); -$pool = CacheManager::getInstance('Memstatic'); +$pool = CacheManager::getInstance('Memory'); $testHelper->printInfoText('Testing APPEND/PREPEND methods...'); { diff --git a/tests/cases/CacheSlamsProtection.test.php b/tests/cases/CacheSlamsProtection.test.php index 20521ebb..5cdb39db 100644 --- a/tests/cases/CacheSlamsProtection.test.php +++ b/tests/cases/CacheSlamsProtection.test.php @@ -14,10 +14,9 @@ use Phpfastcache\CacheManager; use Phpfastcache\Config\IOConfigurationOption; -use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; -use Phpfastcache\Entities\ItemBatch; use Phpfastcache\EventManager; use Phpfastcache\Tests\Helper\TestHelper; +use Phpfastcache\Event\Events; chdir(__DIR__); require_once __DIR__ . '/../../vendor/autoload.php'; @@ -29,8 +28,8 @@ ])); if (!$testHelper->isHHVM()) { - EventManager::getInstance()->onCacheGetItemInSlamBatch(function (ExtendedCacheItemPoolInterface $itemPool, ItemBatch $driverData, $cacheSlamsSpendSeconds) use ($testHelper) { - $testHelper->printText("Looping in batch for {$cacheSlamsSpendSeconds} second(s) with a batch from " . $driverData->getItemDate()->format(\DateTime::W3C)); + EventManager::getInstance()->addListener(Events::CACHE_GET_ITEM_IN_SLAM_BATCH, function (\Phpfastcache\Event\Event\CacheGetItemInSlamBatchItemPoolEvent $event) use ($testHelper) { + $testHelper->printText("Looping in batch for {$event->getCacheSlamsSpendSeconds()} second(s) with a batch from " . $event->getItemBatch()->getItemDate()->format(\DateTime::W3C)); }); $testHelper->runSubProcess('CacheSlamsProtection'); diff --git a/tests/cases/ClusterMasterSlaveReplication.test.php b/tests/cases/ClusterMasterSlaveReplication.test.php index 53d20a87..008198eb 100644 --- a/tests/cases/ClusterMasterSlaveReplication.test.php +++ b/tests/cases/ClusterMasterSlaveReplication.test.php @@ -43,9 +43,10 @@ $cluster = $clusterAggregator->getCluster(AggregatorInterface::STRATEGY_MASTER_SLAVE); $testPasses = false; -$cluster->getEventManager()->onCacheReplicationSlaveFallback( - static function (ExtendedCacheItemPoolInterface $pool, string $actionName) use (&$testPasses) { - if ($actionName === 'getItem') { +$cluster->getEventManager()->addListener( + \Phpfastcache\Event\Events::CACHE_REPLICATION_SLAVE_FALLBACK, + static function (\Phpfastcache\Event\Event\CacheReplicationSlaveFallbackItemPoolEvent $event) use (&$testPasses) { + if ($event->getMethodCaller() === 'getItem') { $testPasses = true; } } diff --git a/tests/cases/EventManagerScoped.test.php b/tests/cases/EventManagerScoped.test.php index 93f499eb..e3d29058 100644 --- a/tests/cases/EventManagerScoped.test.php +++ b/tests/cases/EventManagerScoped.test.php @@ -15,10 +15,10 @@ use Phpfastcache\CacheManager; use Phpfastcache\Core\Item\ExtendedCacheItemInterface; use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; -use Phpfastcache\Event\EventReferenceParameter; use Phpfastcache\EventManager; -use Phpfastcache\Exceptions\PhpfastcacheInvalidTypeException; use Phpfastcache\Tests\Helper\TestHelper; +use Phpfastcache\Event\Event\EventInterface; +use Phpfastcache\Event\Events; chdir(__DIR__); require_once __DIR__ . '/../../vendor/autoload.php'; @@ -36,36 +36,36 @@ $filesGetItemEventManagerCount = 0; $redisGetItemEventManagerCount = 0; -EventManager::getInstance()->addGlobalListener(static function (string $eventName) use ($testHelper, &$globalEveryEventsEvents) { - $testHelper->printInfoText(sprintf('[Global] Global "addGlobalListener" has been called for "%s"', $eventName)); - $globalEveryEventsEvents[$eventName] = ($globalEveryEventsEvents[$eventName] ?? 0) + 1; +EventManager::getInstance()->addGlobalListener(static function (EventInterface $event) use ($testHelper, &$globalEveryEventsEvents) { + $testHelper->printInfoText(sprintf('[Global] Global "addGlobalListener" has been called for "%s"', $event::getName())); + $globalEveryEventsEvents[$event::getName()] = ($globalEveryEventsEvents[$event::getName()] ?? 0) + 1; }, 'GlobalEveryEvent'); -EventManager::getInstance()->onCacheGetItem(static function (ExtendedCacheItemPoolInterface $itemPool, ExtendedCacheItemInterface $item, string $eventName) use ($testHelper, &$globalGetItemEventManagerCount) { +EventManager::getInstance()->addListener(Events::CACHE_GET_ITEM, static function (\Phpfastcache\Event\Event\CacheGetItemEvent $event) use ($testHelper, &$globalGetItemEventManagerCount) { $testHelper->assertPass('[Global] Global event manager received events from multiple pool instances'); $globalGetItemEventManagerCount++; }); -$filesCacheInstance->getEventManager()->addGlobalListener(static function (string $eventName) use ($testHelper, &$filesEveryEventsEventEvents) { - $testHelper->printInfoText(sprintf('[Files] Scoped "addGlobalListener" has been called for "%s"', $eventName)); - $filesEveryEventsEventEvents[$eventName] = ($filesEveryEventsEventEvents[$eventName] ?? 0) + 1; +$filesCacheInstance->getEventManager()->addGlobalListener(static function (EventInterface $event) use ($testHelper, &$filesEveryEventsEventEvents) { + $testHelper->printInfoText(sprintf('[Files] Scoped "addGlobalListener" has been called for "%s"', $event::getName())); + $filesEveryEventsEventEvents[$event::getName()] = ($filesEveryEventsEventEvents[$event::getName()] ?? 0) + 1; }, 'GlobalEveryEvent'); -$filesCacheInstance->getEventManager()->onCacheGetItem(static function (ExtendedCacheItemPoolInterface $itemPool, ExtendedCacheItemInterface $item, string $eventName) use ($testHelper, &$filesGetItemEventManagerCount) { - if($itemPool->getDriverName() === 'Files') { +$filesCacheInstance->getEventManager()->addListener(Events::CACHE_GET_ITEM, static function (\Phpfastcache\Event\Event\CacheGetItemEvent $event) use ($testHelper, &$filesGetItemEventManagerCount) { + if($event->getItemPool()->getDriverName() === 'Files') { $testHelper->assertPass('[Files] Scoped event manager received only events of its own pool instance'); $filesGetItemEventManagerCount++; } }); -$redisCacheInstance->getEventManager()->addGlobalListener(static function (string $eventName) use ($testHelper, &$redisEveryEventsEventEvents) { - $testHelper->printInfoText(sprintf('[Redis] Scoped "addGlobalListener" has been called for "%s"', $eventName)); - $redisEveryEventsEventEvents[$eventName] = ($redisEveryEventsEventEvents[$eventName] ?? 0) + 1; +$redisCacheInstance->getEventManager()->addGlobalListener(static function (\Phpfastcache\Event\Event\EventInterface $event) use ($testHelper, &$redisEveryEventsEventEvents) { + $testHelper->printInfoText(sprintf('[Redis] Scoped "addGlobalListener" has been called for "%s"', $event::getName())); + $redisEveryEventsEventEvents[$event::getName()] = ($redisEveryEventsEventEvents[$event::getName()] ?? 0) + 1; }, 'GlobalEveryEvent'); -$redisCacheInstance->getEventManager()->onCacheGetItem(static function (ExtendedCacheItemPoolInterface $itemPool, ExtendedCacheItemInterface $item, string $eventName) use ($testHelper, &$redisGetItemEventManagerCount) { - if($itemPool->getDriverName() === 'Redis') { +$redisCacheInstance->getEventManager()->addListener(Events::CACHE_GET_ITEM, static function (\Phpfastcache\Event\Event\CacheGetItemEvent $event) use ($testHelper, &$redisGetItemEventManagerCount) { + if($event->getItemPool()->getDriverName() === 'Redis') { $testHelper->assertPass('[Files] Scoped event manager received only events of its own pool instance'); $redisGetItemEventManagerCount++; } diff --git a/tests/cases/GetAllItems.test.php b/tests/cases/GetAllItems.test.php index 6f9ffc3c..9e08e98f 100644 --- a/tests/cases/GetAllItems.test.php +++ b/tests/cases/GetAllItems.test.php @@ -32,9 +32,9 @@ /** * https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV5%CB%96%5D-Fetching-all-keys */ -EventManager::getInstance()->addListener([Events::CACHE_GET_ALL_ITEMS], static function(ExtendedCacheItemPoolInterface $driver, EventReferenceParameter $referenceParameter) use ($testHelper, &$eventFlag){ - $callback = $referenceParameter->getParameterValue(); - $referenceParameter->setParameterValue(function(string $pattern) use ($callback, &$eventFlag, $testHelper) { +EventManager::getInstance()->addListener([Events::CACHE_GET_ALL_ITEMS], static function(\Phpfastcache\Event\Event\CacheGetAllItemsEvent $event) use ($testHelper, &$eventFlag){ + $callback = $event->getEventReferenceParameter()->getParameterValue(); + $event->getEventReferenceParameter()->setParameterValue(function(string $pattern) use ($callback, &$eventFlag, $testHelper) { $eventFlag = true; $testHelper->printInfoText('The custom event Event::CACHE_GET_ALL_ITEMS has been called.'); return $callback($pattern); diff --git a/tests/cases/Memory.test.php b/tests/cases/Memory.test.php index 7aebcdaa..7a4edd67 100644 --- a/tests/cases/Memory.test.php +++ b/tests/cases/Memory.test.php @@ -17,7 +17,7 @@ chdir(__DIR__); require_once __DIR__ . '/../../vendor/autoload.php'; -$testHelper = new TestHelper('Memstatic driver'); +$testHelper = new TestHelper('Memory driver'); $cacheInstance = CacheManager::getInstance('Memory'); $testHelper->runCRUDTests($cacheInstance); diff --git a/tests/cases/Wincache.test.php b/tests/cases/Wincache.test.php deleted file mode 100644 index a43aea8d..00000000 --- a/tests/cases/Wincache.test.php +++ /dev/null @@ -1,28 +0,0 @@ - - * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors - */ - -use Phpfastcache\CacheManager; -use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException; -use Phpfastcache\Tests\Helper\TestHelper; -use Phpfastcache\Drivers\Wincache\Config as WincacheConfig; -use Redis as RedisClient; - -chdir(__DIR__); -require_once __DIR__ . '/../../vendor/autoload.php'; -$testHelper = new TestHelper('Wincache'); - -$cacheInstance = CacheManager::getInstance('Wincache', new WincacheConfig()); -$testHelper->runCRUDTests($cacheInstance); - -$testHelper->terminateTest(); From 23236ab45369a53c41f66b06e4179215f42cfac8 Mon Sep 17 00:00:00 2001 From: Georges Date: Wed, 31 Jan 2024 23:10:41 +0100 Subject: [PATCH 4/6] Rework of events --- README.md | 59 ++---- docs/EVENTS.md | 179 +++++++----------- docs/migration/MigratingFromV9ToV10.md | 13 +- lib/Phpfastcache/Core/Item/CacheItemTrait.php | 1 - .../Event/Event/AbstractItemEvent.php | 6 +- .../Event/Event/AbstractItemPoolEvent.php | 6 +- .../Event/Event/CacheDriverConnectedEvent.php | 4 +- .../Event/Event/CacheGetItemEvent.php | 1 - .../CacheGetItemInSlamBatchItemPoolEvent.php | 6 +- .../Event/Event/CacheItemEventTrait.php | 2 +- .../Event/Event/CacheItemExpireAfterEvent.php | 4 +- .../Event/Event/CacheItemExpireAtEvent.php | 4 +- .../Event/CacheItemPoolEventClusterBuilt.php | 4 +- ...heItemPoolReferenceParameterEventTrait.php | 2 +- .../CacheItemReferenceParameterEventTrait.php | 2 +- .../Event/Event/CacheItemsEventTrait.php | 4 +- ...plicationRandomPoolChosenItemPoolEvent.php | 4 +- ...eReplicationSlaveFallbackItemPoolEvent.php | 4 +- .../CacheWriteFileOnDiskItemPoolEvent.php | 4 +- .../Event/Event/EventInterface.php | 1 - .../Event/EventManagerInterface.php | 11 +- lib/Phpfastcache/Event/EventsInterface.php | 11 +- lib/Phpfastcache/EventManager.php | 32 +--- tests/cases/EventManager.test.php | 2 +- tests/cases/EventManagerScoped.test.php | 4 +- 25 files changed, 145 insertions(+), 225 deletions(-) diff --git a/README.md b/README.md index ae141b80..b223502f 100644 --- a/README.md +++ b/README.md @@ -193,45 +193,25 @@ Internally, the Psr16 adapter calls the Phpfastcache Api via the cache manager. Introducing to events --------------------------- -:mega: As of the V6, Phpfastcache provides an event mechanism. +:mega: As of the V6, Phpfastcache provides an event mechanism.\ You can subscribe to an event by passing a Closure to an active event: ```php onCacheGetItem(function(ExtendedCacheItemPoolInterface $itemPool, ExtendedCacheItemInterface $item){ - $item->set('[HACKED BY EVENT] ' . $item->get()); -}); - -``` - -An event callback can get unbind but you MUST provide a name to the callback previously: - -```php -onCacheGetItem(function(ExtendedCacheItemPoolInterface $itemPool, ExtendedCacheItemInterface $item){ - $item->set('[HACKED BY EVENT] ' . $item->get()); -}, 'myCallbackName'); - - -/** -* Unbind the event callback -*/ -EventManager::getInstance()->unbindEventCallback('onCacheGetItem', 'myCallbackName'); +EventManager::getInstance()->addListener(EventsInterface::CACHE_GET_ITEM, static function(CacheGetItemEvent $event){ + $event->getCacheItem()->set('[HACKED BY EVENT] ' . $item->get()); +}); ``` -:new: As of the **V8** you can simply subscribe to **every** event of Phpfastcache. - +:warning: V10 introduced some notable changes to the event mechanisms.\ More information about the implementation and the events are available on the [Wiki](https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV6%CB%96%5D-Introducing-to-events) --------------------------- @@ -239,8 +219,7 @@ Introducing new helpers --------------------------- :books: As of the V6, Phpfastcache provides some helpers to make your code easier. -- (:warning: Removed in v8, [why ?](https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV6%CB%96%5D-Act-on-all-instances)) ~~The [ActOnAll Helper](https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV6%CB%96%5D-Act-on-all-instances) to help you to act on multiple instance at once.~~ -- The [CacheConditional Helper](https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV6%CB%96%5D-Cache-Conditional) to help you to make the basic conditional statement more easier. +- The [CacheContract](https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV6%CB%96%5D-Cache-Conditional) to help you to make the basic conditional statement easier. - The [Psr16 adapter](https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV6%CB%96%5D-Psr16-adapter) May more will come in the future, feel free to contribute ! @@ -272,7 +251,8 @@ use Phpfastcache\Config\ConfigurationOption; // Please note that as of the V6.1 the "path" config // can also be used for Unix sockets (Redis, Memcache, etc) CacheManager::setDefaultConfig(new ConfigurationOption([ - 'path' => '/var/www/phpfastcache.com/dev/tmp', // or in windows "C:/tmp/" + 'defaultTtl' => 900, + 'defaultTtl' => '/var/www/phpfastcache.com/dev/tmp', // or in windows "C:/tmp/" ])); // In your class, function, you can call the Cache @@ -283,7 +263,7 @@ $InstanceCache = CacheManager::getInstance('files'); * product_page is "identity keyword"; */ $key = "product_page"; -$CachedString = $InstanceCache->getItem($key); +$cacheItem = $InstanceCache->getItem($key); $your_product_data = [ 'First product', @@ -292,30 +272,25 @@ $your_product_data = [ /* ... */ ]; -if (!$CachedString->isHit()) { - $CachedString->set($your_product_data)->expiresAfter(5);//in seconds, also accepts Datetime - $InstanceCache->save($CachedString); // Save the cache item just like you do with doctrine and entities +if (!$cacheItem->isHit()) { + $cacheItem->set($your_product_data)->expiresAfter(5);//in seconds, also accepts Datetime + $cacheItem->save($cacheItem); // Save the cache item just like you do with doctrine and entities echo 'FIRST LOAD // WROTE OBJECT TO CACHE // RELOAD THE PAGE AND SEE // '; - echo $CachedString->get(); + echo $cacheItem->get(); } else { echo 'READ FROM CACHE // '; - echo $CachedString->get()[0];// Will print 'First product' + echo $cacheItem->get()[0];// Will print 'First product' } /** * use your products here or return them; */ -echo implode('
', $CachedString->get());// Will echo your product list +echo implode('
', $cacheItem->get());// Will echo your product list ``` -##### :floppy_disk: Legacy support (Without Composer) -~~* See the file examples/withoutComposer.php for more information.~~\ -:warning: The legacy autoload will be removed in the next major release :warning:\ -Please include Phpfastcache through composer by running `composer require phpfastcache/phpfastcache`. - #### :zap: Step 3: Enjoy ! Your website is now faster than lightning ! For curious developers, there is a lot of other examples available [here](./docs/examples). diff --git a/docs/EVENTS.md b/docs/EVENTS.md index 88477acc..99da8ec3 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -1,85 +1,50 @@ :mega: As of the V6, Phpfastcache provides an event mechanism. -You can subscribe to an event by passing a Closure to an active event: +You can subscribe to an event by passing a Closure/Callable to an active event: ```php use Phpfastcache\EventManager; /** -* Bind the event callback +* Bind the listener */ -EventManager::getInstance()->onCacheGetItem(function(ExtendedCacheItemPoolInterface $itemPool, ExtendedCacheItemInterface $item){ - $item->set('[HACKED BY EVENT] ' . $item->get()); +use Phpfastcache\Event\EventsInterface; +use Phpfastcache\Event\Event\CacheGetItemEvent; + +EventManager::getInstance()->addListener(EventsInterface::CACHE_GET_ITEM, static function(CacheGetItemEvent $event){ + $event->getCacheItem()->set('[HACKED BY EVENT] ' . $item->get()); }); ``` -An event callback can get unbind but you MUST provide a name to the callback previously: - - -```php -use Phpfastcache\EventManager; - -/** -* Bind the event callback -*/ -EventManager::getInstance()->onCacheGetItem(function(ExtendedCacheItemPoolInterface $itemPool, ExtendedCacheItemInterface $item){ - $item->set('[HACKED BY EVENT] ' . $item->get()); -}, 'myCallbackName'); - +~~An event callback can get unbind, but you MUST provide a name to the callback previously:~~ +**/!\ Method `unbindEventCallback` has been removed as of V10.** -/** -* Unbind the event callback -*/ -EventManager::getInstance()->unbindEventCallback('onCacheGetItem', 'myCallbackName'); - -``` :new: in V8 +You can simply subscribe to **every** event at once of Phpfastcache. -You can simply subscribe to **every** events at once of Phpfastcache. ```php onEveryEvents(static function (string $eventName, ...$args) { - echo sprintf("Triggered event '{$eventName}' with %d arguments provided", count($args)); -}, 'debugCallback'); +EventManager::getInstance()->addGlobalListener(static function (\Phpfastcache\Event\Event\EventInterface $event) { + echo sprintf('Triggered event %s', $event->getName()); +}); ``` This is an exhaustive list, and it will be updated as soon as new events will be added to the Core. +:warning: Changed in V10: -:new: In V9 - -- Some callback parameter, that are __NOT__ objects, are passed by reference via the new `\Phpfastcache\Event\EventReferenceParameter` class.\ - This class is instantiated and passed to the callback with the original value passed **by reference** allowing you to either read or re-write its value.\ - If it's allowed by the event dispatcher the type can be changed or not.\ - If you try to while it's not allowed, you will get a `PhpfastcacheInvalidArgumentException` when trying to call `\Phpfastcache\Event\EventReferenceParameter::setParameterValue()`\ - Finally the class `\Phpfastcache\Event\EventReferenceParameter` is `invokable` and trying to do so will return you the parameter value.\ -- A method named `unbindAllEventCallbacks(): bool` has been added to `EventManagerInterface` to allow you to unbind/clear all event from an event instance. -- Event callbacks will now receive the `eventName` as an extra _last_ callback parameter (except for `onEveryEvents` callbacks) -- Added `EventManagerInterface::on(array $eventNames, $callback)` method, to subscribe to multiple events in once with the same callback - -:warning: Changed in V9.2 - -As of the V9.2 there is a slight change with the EventManager: -EventManager is now scoped to its own poll if retrieved through `ExtendedCacheItemPoolTrait::->getEventManager()`. -This means, that the behavior is not more consistent:\ -An EventManager retrieved through `ExtendedCacheItemPoolTrait::->getEventManager()` will now **ONLY** fire events related to this pool instance.\ -However, the global EventManager `EventManager::getInstance()` remains unchanged and will fire any events no matter what pool emitted it. -The order of execution of the events is always the following: - -1. Scoped named Event through `ExtendedCacheItemPoolTrait::->getEventManager()->onXxxxxXxxxx(...)` -2. Scoped `onEveryEvent` Event through `ExtendedCacheItemPoolTrait::->getEventManager()->onEveryEvent(...)` -3. Unscoped named event through `EventManager::getInstance()->onXxxxxXxxxx(...)` -4. Unscoped `onEveryEvent` event through `EventManager::getInstance()->onEveryEvent(...)` +1. Method `onEveryEvent` is DEPRECATED and changed its name. It is now called `addGlobalListener`. +2. Method `unbindAllEventCallbacks` has been renamed to `unbindAllListeners`. +3. Methods `onXxxxxxXxxxx` are now DEPRECATED. Use method `addListener()` instead. ## List of active events: ### ItemPool Events -- onCacheGetItem(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_GET_ITEM, *Callable* **$callback**) - **Callback arguments** - - *ExtendedCacheItemPoolInterface* **$itemPool** - - *ExtendedCacheItemInterface* **$item** + - *\Phpfastcache\Event\Event\CacheGetItemEvent* **$event** - **Scope** - ItemPool - **Description** @@ -90,10 +55,9 @@ The order of execution of the events is always the following: - *ExtendedCacheItemPoolInterface::getItemsByTag()* - *ExtendedCacheItemPoolInterface::getItemsAsJsonString()* -- onCacheGetItems(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_GET_ITEMS, *Callable* **$callback**) - **Callback arguments** - - *ExtendedCacheItemPoolInterface* **$itemPool** - - *ExtendedCacheItemInterface[]* **$items** + - *\Phpfastcache\Event\Event\CacheGetItemsEvent* **$event** - **Scope** - ItemPool - **Description** @@ -104,14 +68,26 @@ The order of execution of the events is always the following: - *ExtendedCacheItemPoolInterface::getItemsByTag()* - *ExtendedCacheItemPoolInterface::getItemsAsJsonString()* -- onCacheDeleteItem(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_GET_ALL_ITEMS, *Callable* **$callback**) + - **Callback arguments** + - *\Phpfastcache\Event\Event\CacheGetAllItemsEvent* **$event** + - **Scope** + - ItemPool + - **Description** + - Allow you to manipulate a set of cache keys just before they get fetched from the backend. + - **Risky Circular Methods** + - *ExtendedCacheItemPoolInterface::getItem()* + - *ExtendedCacheItemPoolInterface::getItems()* + - *ExtendedCacheItemPoolInterface::getItemsByTag()* + - *ExtendedCacheItemPoolInterface::getItemsAsJsonString()* + +- addListener(EventsInterface::CACHE_DELETE_ITEM, *Callable* **$callback**) - **Callback arguments** - - *ExtendedCacheItemPoolInterface* **$itemPool** - - *ExtendedCacheItemInterface* **$item** + - *\Phpfastcache\Event\Event\CacheDeleteItemEvent* **$event** - **Scope** - ItemPool - **Description** - - Allow you to manipulate an item after being deleted (this event is not fired if `deleteItems()` is called). :exclamation: **Caution** The provided item is in pool detached-state. + - Allow you to manipulate an item after being deleted (this event is not fired if `deleteItems()` is called). :exclamation: **Caution** The provided item is in pool-detached state. - **Risky Circular Methods** - *ExtendedCacheItemPoolInterface::deleteItem()* - *ExtendedCacheItemPoolInterface::deleteItems()* @@ -120,10 +96,9 @@ The order of execution of the events is always the following: - *ExtendedCacheItemPoolInterface::getItemsByTag()* - *ExtendedCacheItemPoolInterface::getItemsAsJsonString()* -- onCacheDeleteItems(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_DELETE_ITEMS, *Callable* **$callback**) - **Callback arguments** - - *ExtendedCacheItemPoolInterface* **$itemPool** - - *ExtendedCacheItemInterface[]* **$items** + - *\Phpfastcache\Event\Event\CacheDeleteItemsEvent* **$event** - **Scope** - ItemPool - **Description** @@ -136,10 +111,9 @@ The order of execution of the events is always the following: - *ExtendedCacheItemPoolInterface::getItemsByTag()* - *ExtendedCacheItemPoolInterface::getItemsAsJsonString()* -- onCacheSaveItem(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_SAVE_ITEM, *Callable* **$callback**) - **Callback arguments** - - *ExtendedCacheItemPoolInterface* **$itemPool** - - *ExtendedCacheItemInterface* **$item** + - *\Phpfastcache\Event\Event\CacheSaveItemEvent* **$event** - **Scope** - ItemPool - **Description** @@ -148,10 +122,9 @@ The order of execution of the events is always the following: - *ExtendedCacheItemPoolInterface::commit()* - *ExtendedCacheItemPoolInterface::save()* -- onCacheSaveMultipleItems(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_SAVE_MULTIPLE_ITEMS, *Callable* **$callback**) - **Callback arguments** - - *ExtendedCacheItemPoolInterface* **$itemPool** - - *EventReferenceParameter($items)* **$items** _via EventReferenceParameter object_ **(type modification forbidden)** + - *\Phpfastcache\Event\EventCacheSaveMultipleItemsEvent* **$event** - **Scope** - ItemPool - **Description** @@ -161,10 +134,9 @@ The order of execution of the events is always the following: - *ExtendedCacheItemPoolInterface::save()* - *ExtendedCacheItemPoolInterface::saveMultiple()* -- onCacheSaveDeferredItem(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_SAVE_DEFERRED_ITEM, (*Callable* **$callback**) - **Callback arguments** - - *ExtendedCacheItemPoolInterface* **$itemPool** - - *ExtendedCacheItemInterface* **$item** + - *\Phpfastcache\Event\CacheSaveDeferredItemEvent* **$event** - **Scope** - ItemPool - **Description** @@ -172,10 +144,9 @@ The order of execution of the events is always the following: - **Risky Circular Methods** - *ExtendedCacheItemPoolInterface::saveDeferred()* -- onCacheCommitItem(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_COMMIT_ITEM, *Callable* **$callback**) - **Callback arguments** - - *ExtendedCacheItemPoolInterface* **$itemPool** - - *EventReferenceParameter($items)* **$items** _via EventReferenceParameter object_ **(type modification forbidden)** + - *\Phpfastcache\Event\CacheCommitItemEvent* **$event** - **Scope** - ItemPool - **Description** @@ -183,10 +154,9 @@ The order of execution of the events is always the following: - **Risky Circular Methods** - *ExtendedCacheItemPoolInterface::commit()* -- onCacheClearItem(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_CLEAR_ITEMS, *Callable* **$callback**) - **Callback arguments** - - *ExtendedCacheItemPoolInterface* **$itemPool** - - *ExtendedCacheItemInterface[]* **$items** + - *\Phpfastcache\Event\CacheClearItemsEvent* **$event** - **Scope** - ItemPool - **Description** @@ -195,11 +165,9 @@ The order of execution of the events is always the following: - *ExtendedCacheItemPoolInterface::clear()* - *ExtendedCacheItemPoolInterface::clean()* - - onCacheWriteFileOnDisk(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_WRITE_FILE_ON_DISK, *Callable* **$callback**) - **Callback arguments** - - *ExtendedCacheItemPoolInterface* **$itemPool** - - *string* **$file** - - *bool* **$secureFileManipulation** + - *\Phpfastcache\Event\CacheWriteFileOnDiskEvent* **$event** - **Scope** - ItemPool - **Description** @@ -207,11 +175,9 @@ The order of execution of the events is always the following: - **Risky Circular Methods** - *ExtendedCacheItemPoolInterface::writefile()* -- onCacheGetItemInSlamBatch(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_GET_ITEM_IN_SLAM_BATCH, *Callable* **$callback**) - **Callback arguments** - - *ExtendedCacheItemPoolInterface* **$itemPool** - - *ItemBatch* **$driverData** - - *int* **$cacheSlamsSpendSeconds** + - *\Phpfastcache\Event\CacheGetItemInSlamBatchEvent* **$event** - **Scope** - ItemPool - **Description** @@ -223,19 +189,18 @@ The order of execution of the events is always the following: - *ExtendedCacheItemPoolInterface::getItemsByTag()* - *ExtendedCacheItemPoolInterface::getItemsAsJsonString()* -- onCacheDriverChecked(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_DRIVER_CHECKED, **$callback**) - **Callback arguments** - - *ExtendedCacheItemPoolInterface* **$itemPool** + - *\Phpfastcache\Event\CacheDriverCheckedEvent* **$event** - **Scope** - ItemPool - **Description** - Allow you to bind an event when the driver prerequisites has passed but before it the `driverConnect()` is called. - **Risky Circular Methods** - *(none)* -- onCacheDriverConnected(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_DRIVER_CONNECTED, *Callable* **$callback**) - **Callback arguments** - - *ExtendedCacheItemPoolInterface* **$itemPool** - - *object* **$instance** Internal instance of the backend connect + - *\Phpfastcache\Event\CacheDriverConnectedEvent* **$event** - **Scope** - ItemPool - **Description** @@ -243,10 +208,9 @@ The order of execution of the events is always the following: - **Risky Circular Methods** - *(none)* ### ItemPool Events (Cluster) -- onCacheReplicationSlaveFallback(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_GET_ITEM_IN_SLAM_BATCH, *Callable* **$callback**) - **Callback arguments** - - *ClusterPoolInterface* **$self** - - *string* **$caller** + - *\Phpfastcache\Event\CacheReplicationSlaveFallbackEvent* **$event** - **Scope** - Cluster pool - **Description** @@ -254,10 +218,9 @@ The order of execution of the events is always the following: - **Risky Circular Methods** - N/A -- onCacheReplicationRandomPoolChosen(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_REPLICATION_RANDOM_POOL_CHOSEN, *Callable* **$callback**) - **Callback arguments** - - *ClusterPoolInterface* **$self** - - *ExtendedCacheItemPoolInterface* **$randomPool** + - *\Phpfastcache\Event\CacheReplicationRandomPoolChosenEvent* **$event** - **Scope** - Cluster pool - **Description** @@ -265,10 +228,9 @@ The order of execution of the events is always the following: - **Risky Circular Methods** - N/A -- onCacheClusterBuilt(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_CLUSTER_BUILT, *Callable* **$callback**) - **Callback arguments** - - *AggregatorInterface* **$clusterAggregator** - - *ClusterPoolInterface* **$cluster** + - *\Phpfastcache\Event\CacheClusterBuiltEvent* **$event** - **Scope** - Cluster aggregator - **Description** @@ -276,10 +238,9 @@ The order of execution of the events is always the following: - **Risky Circular Methods** - *$clusterAggregator::getCluster()* ### Item Events -- onCacheItemSet(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_ITEM_SET, *Callable* **$callback**) - **Callback arguments** - - *ExtendedCacheItemInterface* **$item** - - *EventReferenceParameter($value)* **$value** _via EventReferenceParameter object_ **(type modification allowed)** + - *\Phpfastcache\Event\CacheItemSetEvent* **$event** - **Scope** - Item - **Description** @@ -287,10 +248,9 @@ The order of execution of the events is always the following: - **Risky Circular Methods** - *ExtendedCacheItemInterface::get()* -- onCacheItemExpireAt(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_ITEM_EXPIRE_AT, *Callable* **$callback**) - **Callback arguments** - - *ExtendedCacheItemInterface* **$item** - - *\DateTimeInterface* **$expiration** + - *\Phpfastcache\Event\CacheItemExpireAtEvent* **$event** - **Scope** - Item - **Description** @@ -298,10 +258,9 @@ The order of execution of the events is always the following: - **Risky Circular Methods** - *ExtendedCacheItemInterface::expiresAt()* -- onCacheItemExpireAfter(*Callable* **$callback**) +- addListener(EventsInterface::CACHE_ITEM_EXPIRE_AFTER, *Callable* **$callback**) - **Callback arguments** - - *ExtendedCacheItemInterface* **$item** - - *int | \DateInterval* **$time** + - *\Phpfastcache\Event\CacheItemExpireAfterEvent* **$event** - **Scope** - Item - **Description** diff --git a/docs/migration/MigratingFromV9ToV10.md b/docs/migration/MigratingFromV9ToV10.md index 206e08b5..0e60013f 100644 --- a/docs/migration/MigratingFromV9ToV10.md +++ b/docs/migration/MigratingFromV9ToV10.md @@ -2,7 +2,18 @@ Because the V10 is **relatively** not backward compatible with the V9, here's a ### :warning: Minimum php version increased to 8.2+ As of the V9 the mandatory php version has been increased to 8.2+. -Once released, the php versions 8.3, 8.4 will be unit-tested +Once released, the php versions 8.3, 8.4 will be unit-tested + + +### :warning: Important changes in Event mechanisms +#### EventManager and its event now implements the [PSR-14: Event Dispatcher](https://www.php-fig.org/psr/psr-14/) +Which means there's some unavoidable and backward breaking changes: + +1. Method `onEveryEvent` is DEPRECATED and changed its name. It is now called `addGlobalListener`. +2. Method `unbindAllEventCallbacks` has been renamed to `unbindAllListeners`. +3. Method `unbindEventCallback` has been removed. +4. Methods `onXxxxxxXxxxx` are now DEPRECATED. Use method `addListener()` instead. See the list of available events in `Phpfastcache\Event\EventsInterface`; +5. Callback now receive an `\Phpfastcache\Event\Event\EventInterface` object as their unique parameter. The exact object name depends of the event you subscribed on. ### Added Microsoft Azure Cosmos DB driver Extension Cosmosdb has been added has an extension: `phpfastcache/cosmosdb-extension`. diff --git a/lib/Phpfastcache/Core/Item/CacheItemTrait.php b/lib/Phpfastcache/Core/Item/CacheItemTrait.php index 122e5c8a..20d3150d 100644 --- a/lib/Phpfastcache/Core/Item/CacheItemTrait.php +++ b/lib/Phpfastcache/Core/Item/CacheItemTrait.php @@ -22,7 +22,6 @@ use Phpfastcache\Event\Event\CacheItemSetEvent; use Phpfastcache\Event\Event\CacheItemExpireAfterEvent; use Phpfastcache\Event\Event\CacheItemExpireAtEvent; -use Phpfastcache\Event\Events; use Phpfastcache\Event\EventManagerDispatcherTrait; use Phpfastcache\Event\EventReferenceParameter; use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException; diff --git a/lib/Phpfastcache/Event/Event/AbstractItemEvent.php b/lib/Phpfastcache/Event/Event/AbstractItemEvent.php index 63172cb9..b64a542d 100644 --- a/lib/Phpfastcache/Event/Event/AbstractItemEvent.php +++ b/lib/Phpfastcache/Event/Event/AbstractItemEvent.php @@ -25,12 +25,12 @@ public static function getName(): string return static::EVENT_NAME; } - public function __construct(protected ExtendedCacheItemInterface $item) + public function __construct(protected ExtendedCacheItemInterface $cacheItem) { } - public function getItem(): ExtendedCacheItemInterface + public function getCacheItem(): ExtendedCacheItemInterface { - return $this->item; + return $this->cacheItem; } } diff --git a/lib/Phpfastcache/Event/Event/AbstractItemPoolEvent.php b/lib/Phpfastcache/Event/Event/AbstractItemPoolEvent.php index 9db77be6..3989bff3 100644 --- a/lib/Phpfastcache/Event/Event/AbstractItemPoolEvent.php +++ b/lib/Phpfastcache/Event/Event/AbstractItemPoolEvent.php @@ -25,12 +25,12 @@ public static function getName(): string return static::EVENT_NAME; } - public function __construct(protected ExtendedCacheItemPoolInterface $itemPool) + public function __construct(protected ExtendedCacheItemPoolInterface $cachePool) { } - public function getItemPool(): ExtendedCacheItemPoolInterface + public function getCachePool(): ExtendedCacheItemPoolInterface { - return $this->itemPool; + return $this->cachePool; } } diff --git a/lib/Phpfastcache/Event/Event/CacheDriverConnectedEvent.php b/lib/Phpfastcache/Event/Event/CacheDriverConnectedEvent.php index 27a899d1..374e11ea 100644 --- a/lib/Phpfastcache/Event/Event/CacheDriverConnectedEvent.php +++ b/lib/Phpfastcache/Event/Event/CacheDriverConnectedEvent.php @@ -23,9 +23,9 @@ class CacheDriverConnectedEvent extends AbstractItemPoolEvent { public const EVENT_NAME = EventsInterface::CACHE_DRIVER_CONNECTED; - public function __construct(ExtendedCacheItemPoolInterface $itemPool, protected ?object $driverInstance) + public function __construct(ExtendedCacheItemPoolInterface $cachePool, protected ?object $driverInstance) { - parent::__construct($itemPool); + parent::__construct($cachePool); } /** diff --git a/lib/Phpfastcache/Event/Event/CacheGetItemEvent.php b/lib/Phpfastcache/Event/Event/CacheGetItemEvent.php index dab72297..6dbd3260 100644 --- a/lib/Phpfastcache/Event/Event/CacheGetItemEvent.php +++ b/lib/Phpfastcache/Event/Event/CacheGetItemEvent.php @@ -16,7 +16,6 @@ namespace Phpfastcache\Event\Event; -use Phpfastcache\Core\Item\ExtendedCacheItemInterface; use Phpfastcache\Event\EventsInterface; class CacheGetItemEvent extends AbstractItemPoolEvent diff --git a/lib/Phpfastcache/Event/Event/CacheGetItemInSlamBatchItemPoolEvent.php b/lib/Phpfastcache/Event/Event/CacheGetItemInSlamBatchItemPoolEvent.php index 0bb7fdee..970419cb 100644 --- a/lib/Phpfastcache/Event/Event/CacheGetItemInSlamBatchItemPoolEvent.php +++ b/lib/Phpfastcache/Event/Event/CacheGetItemInSlamBatchItemPoolEvent.php @@ -24,9 +24,9 @@ class CacheGetItemInSlamBatchItemPoolEvent extends AbstractItemPoolEvent { public const EVENT_NAME = EventsInterface::CACHE_GET_ITEM_IN_SLAM_BATCH; - public function __construct(ExtendedCacheItemPoolInterface $itemPool, protected ItemBatch $itemBatch, protected float|int $cacheSlamsSpendSeconds) + public function __construct(ExtendedCacheItemPoolInterface $cachePool, protected ItemBatch $cacheItemBatch, protected float|int $cacheSlamsSpendSeconds) { - parent::__construct($itemPool); + parent::__construct($cachePool); } /** @@ -34,7 +34,7 @@ public function __construct(ExtendedCacheItemPoolInterface $itemPool, protected */ public function getItemBatch(): ItemBatch { - return $this->itemBatch; + return $this->cacheItemBatch; } /** diff --git a/lib/Phpfastcache/Event/Event/CacheItemEventTrait.php b/lib/Phpfastcache/Event/Event/CacheItemEventTrait.php index 79ae689e..92dc630a 100644 --- a/lib/Phpfastcache/Event/Event/CacheItemEventTrait.php +++ b/lib/Phpfastcache/Event/Event/CacheItemEventTrait.php @@ -22,7 +22,7 @@ trait CacheItemEventTrait { - public function __construct(protected ExtendedCacheItemPoolInterface $itemPool, protected ExtendedCacheItemInterface|CacheItemInterface $cacheItem) + public function __construct(protected ExtendedCacheItemPoolInterface $cachePool, protected ExtendedCacheItemInterface|CacheItemInterface $cacheItem) { } diff --git a/lib/Phpfastcache/Event/Event/CacheItemExpireAfterEvent.php b/lib/Phpfastcache/Event/Event/CacheItemExpireAfterEvent.php index 1c113595..fb97d0c5 100644 --- a/lib/Phpfastcache/Event/Event/CacheItemExpireAfterEvent.php +++ b/lib/Phpfastcache/Event/Event/CacheItemExpireAfterEvent.php @@ -23,9 +23,9 @@ class CacheItemExpireAfterEvent extends AbstractItemEvent { public const EVENT_NAME = EventsInterface::CACHE_ITEM_EXPIRE_AFTER; - public function __construct(ExtendedCacheItemInterface $item, protected int|\DateInterval|null $expireAfter) + public function __construct(ExtendedCacheItemInterface $cacheItem, protected int|\DateInterval|null $expireAfter) { - parent::__construct($item); + parent::__construct($cacheItem); } /** diff --git a/lib/Phpfastcache/Event/Event/CacheItemExpireAtEvent.php b/lib/Phpfastcache/Event/Event/CacheItemExpireAtEvent.php index c284dba0..7d952ef9 100644 --- a/lib/Phpfastcache/Event/Event/CacheItemExpireAtEvent.php +++ b/lib/Phpfastcache/Event/Event/CacheItemExpireAtEvent.php @@ -24,9 +24,9 @@ class CacheItemExpireAtEvent extends AbstractItemEvent { public const EVENT_NAME = EventsInterface::CACHE_ITEM_EXPIRE_AT; - public function __construct(ExtendedCacheItemInterface $item, protected \DateTimeInterface $expireAt) + public function __construct(ExtendedCacheItemInterface $cacheItem, protected \DateTimeInterface $expireAt) { - parent::__construct($item); + parent::__construct($cacheItem); } /** diff --git a/lib/Phpfastcache/Event/Event/CacheItemPoolEventClusterBuilt.php b/lib/Phpfastcache/Event/Event/CacheItemPoolEventClusterBuilt.php index e9382625..cec5e274 100644 --- a/lib/Phpfastcache/Event/Event/CacheItemPoolEventClusterBuilt.php +++ b/lib/Phpfastcache/Event/Event/CacheItemPoolEventClusterBuilt.php @@ -24,9 +24,9 @@ class CacheItemPoolEventClusterBuilt extends AbstractItemPoolEvent { public const EVENT_NAME = EventsInterface::CACHE_CLUSTER_BUILT; - public function __construct(ExtendedCacheItemPoolInterface $itemPool, protected AggregatorInterface $clusterAggregator) + public function __construct(ExtendedCacheItemPoolInterface $cachePool, protected AggregatorInterface $clusterAggregator) { - parent::__construct($itemPool); + parent::__construct($cachePool); } /** diff --git a/lib/Phpfastcache/Event/Event/CacheItemPoolReferenceParameterEventTrait.php b/lib/Phpfastcache/Event/Event/CacheItemPoolReferenceParameterEventTrait.php index 14b5b57f..bc750ae0 100644 --- a/lib/Phpfastcache/Event/Event/CacheItemPoolReferenceParameterEventTrait.php +++ b/lib/Phpfastcache/Event/Event/CacheItemPoolReferenceParameterEventTrait.php @@ -24,7 +24,7 @@ */ trait CacheItemPoolReferenceParameterEventTrait { - public function __construct(protected ExtendedCacheItemPoolInterface $itemPool, protected EventReferenceParameter $eventReferenceParameter) + public function __construct(protected ExtendedCacheItemPoolInterface $cachePool, protected EventReferenceParameter $eventReferenceParameter) { } diff --git a/lib/Phpfastcache/Event/Event/CacheItemReferenceParameterEventTrait.php b/lib/Phpfastcache/Event/Event/CacheItemReferenceParameterEventTrait.php index 12d41287..8901a356 100644 --- a/lib/Phpfastcache/Event/Event/CacheItemReferenceParameterEventTrait.php +++ b/lib/Phpfastcache/Event/Event/CacheItemReferenceParameterEventTrait.php @@ -21,7 +21,7 @@ trait CacheItemReferenceParameterEventTrait { - public function __construct(protected ExtendedCacheItemInterface $item, protected EventReferenceParameter $eventReferenceParameter) + public function __construct(protected ExtendedCacheItemInterface $cacheItem, protected EventReferenceParameter $eventReferenceParameter) { } diff --git a/lib/Phpfastcache/Event/Event/CacheItemsEventTrait.php b/lib/Phpfastcache/Event/Event/CacheItemsEventTrait.php index 67fbdebd..872a5925 100644 --- a/lib/Phpfastcache/Event/Event/CacheItemsEventTrait.php +++ b/lib/Phpfastcache/Event/Event/CacheItemsEventTrait.php @@ -23,10 +23,10 @@ trait CacheItemsEventTrait { /** - * @param ExtendedCacheItemPoolInterface $itemPool + * @param ExtendedCacheItemPoolInterface $cachePool * @param array $cacheItems */ - public function __construct(protected ExtendedCacheItemPoolInterface $itemPool, protected array $cacheItems) + public function __construct(protected ExtendedCacheItemPoolInterface $cachePool, protected array $cacheItems) { } diff --git a/lib/Phpfastcache/Event/Event/CacheReplicationRandomPoolChosenItemPoolEvent.php b/lib/Phpfastcache/Event/Event/CacheReplicationRandomPoolChosenItemPoolEvent.php index 518a5b76..93d5d3b7 100644 --- a/lib/Phpfastcache/Event/Event/CacheReplicationRandomPoolChosenItemPoolEvent.php +++ b/lib/Phpfastcache/Event/Event/CacheReplicationRandomPoolChosenItemPoolEvent.php @@ -26,9 +26,9 @@ class CacheReplicationRandomPoolChosenItemPoolEvent extends AbstractItemPoolEven { public const EVENT_NAME = EventsInterface::CACHE_REPLICATION_RANDOM_POOL_CHOSEN; - public function __construct(ExtendedCacheItemPoolInterface $itemPool, protected ExtendedCacheItemPoolInterface $randomPool) + public function __construct(ExtendedCacheItemPoolInterface $cachePool, protected ExtendedCacheItemPoolInterface $randomPool) { - parent::__construct($itemPool); + parent::__construct($cachePool); } /** diff --git a/lib/Phpfastcache/Event/Event/CacheReplicationSlaveFallbackItemPoolEvent.php b/lib/Phpfastcache/Event/Event/CacheReplicationSlaveFallbackItemPoolEvent.php index 41abb528..37d2e0db 100644 --- a/lib/Phpfastcache/Event/Event/CacheReplicationSlaveFallbackItemPoolEvent.php +++ b/lib/Phpfastcache/Event/Event/CacheReplicationSlaveFallbackItemPoolEvent.php @@ -26,9 +26,9 @@ class CacheReplicationSlaveFallbackItemPoolEvent extends AbstractItemPoolEvent { public const EVENT_NAME = EventsInterface::CACHE_REPLICATION_SLAVE_FALLBACK; - public function __construct(ExtendedCacheItemPoolInterface $itemPool, protected string $methodCaller) + public function __construct(ExtendedCacheItemPoolInterface $cachePool, protected string $methodCaller) { - parent::__construct($itemPool); + parent::__construct($cachePool); } /** diff --git a/lib/Phpfastcache/Event/Event/CacheWriteFileOnDiskItemPoolEvent.php b/lib/Phpfastcache/Event/Event/CacheWriteFileOnDiskItemPoolEvent.php index 2e6dbdb6..37baaa23 100644 --- a/lib/Phpfastcache/Event/Event/CacheWriteFileOnDiskItemPoolEvent.php +++ b/lib/Phpfastcache/Event/Event/CacheWriteFileOnDiskItemPoolEvent.php @@ -23,9 +23,9 @@ class CacheWriteFileOnDiskItemPoolEvent extends AbstractItemPoolEvent { public const EVENT_NAME = EventsInterface::CACHE_WRITE_FILE_ON_DISK; - public function __construct(ExtendedCacheItemPoolInterface $itemPool, protected string $file) + public function __construct(ExtendedCacheItemPoolInterface $cachePool, protected string $file) { - parent::__construct($itemPool); + parent::__construct($cachePool); } /** diff --git a/lib/Phpfastcache/Event/Event/EventInterface.php b/lib/Phpfastcache/Event/Event/EventInterface.php index 82a3084d..a0e54c5d 100644 --- a/lib/Phpfastcache/Event/Event/EventInterface.php +++ b/lib/Phpfastcache/Event/Event/EventInterface.php @@ -16,7 +16,6 @@ namespace Phpfastcache\Event\Event; -use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; use Psr\EventDispatcher\StoppableEventInterface; interface EventInterface extends StoppableEventInterface diff --git a/lib/Phpfastcache/Event/EventManagerInterface.php b/lib/Phpfastcache/Event/EventManagerInterface.php index 5773377b..6962305c 100644 --- a/lib/Phpfastcache/Event/EventManagerInterface.php +++ b/lib/Phpfastcache/Event/EventManagerInterface.php @@ -51,7 +51,7 @@ public function __call(string $name, array $arguments): void; * @param callable $callback * @param string $callbackName */ - public function addGlobalListener(callable $callback, string $callbackName): void; + public function addGlobalListener(callable $callback): void; /** * @param string[]|string $events @@ -59,17 +59,10 @@ public function addGlobalListener(callable $callback, string $callbackName): voi */ public function addListener(array|string $events, callable $callback): void; - /** - * @param string $eventName - * @param string $callbackName - * @return bool - */ - public function unbindEventCallback(string $eventName, string $callbackName): bool; - /** * @return bool */ - public function unbindAllEventCallbacks(): bool; + public function unbindAllListeners(): void; /** * @param ExtendedCacheItemPoolInterface $pool diff --git a/lib/Phpfastcache/Event/EventsInterface.php b/lib/Phpfastcache/Event/EventsInterface.php index f3b67de4..d19e603f 100644 --- a/lib/Phpfastcache/Event/EventsInterface.php +++ b/lib/Phpfastcache/Event/EventsInterface.php @@ -18,8 +18,10 @@ interface EventsInterface { + // ItemPool Events public const CACHE_GET_ITEM = 'CacheGetItem'; public const CACHE_GET_ITEMS = 'CacheGetItems'; + public const CACHE_GET_ALL_ITEMS = 'CacheGetAllItems'; public const CACHE_DELETE_ITEM = 'CacheDeleteItem'; public const CACHE_DELETE_ITEMS = 'CacheDeleteItems'; public const CACHE_SAVE_ITEM = 'CacheSaveItem'; @@ -29,15 +31,18 @@ interface EventsInterface public const CACHE_CLEAR_ITEMS = 'CacheClearItems'; public const CACHE_WRITE_FILE_ON_DISK = 'CacheWriteFileOnDisk'; public const CACHE_GET_ITEM_IN_SLAM_BATCH = 'CacheGetItemInSlamBatch'; + public const CACHE_DRIVER_CHECKED = 'CacheDriverChecked'; + public const CACHE_DRIVER_CONNECTED = 'CacheDriverConnected'; + + // ItemPool Events (Cluster) public const CACHE_REPLICATION_SLAVE_FALLBACK = 'CacheReplicationSlaveFallback'; public const CACHE_REPLICATION_RANDOM_POOL_CHOSEN = 'CacheReplicationRandomPoolChosen'; public const CACHE_CLUSTER_BUILT = 'CacheClusterBuilt'; + + // Item Events public const CACHE_ITEM_SET = 'CacheItemSet'; public const CACHE_ITEM_EXPIRE_AT = 'CacheItemExpireAt'; public const CACHE_ITEM_EXPIRE_AFTER = 'CacheItemExpireAfter'; - public const CACHE_GET_ALL_ITEMS = 'CacheGetAllItems'; - public const CACHE_DRIVER_CHECKED = 'CacheDriverChecked'; - public const CACHE_DRIVER_CONNECTED = 'CacheDriverConnected'; /** * @return array diff --git a/lib/Phpfastcache/EventManager.php b/lib/Phpfastcache/EventManager.php index cbc041d5..59a03bec 100644 --- a/lib/Phpfastcache/EventManager.php +++ b/lib/Phpfastcache/EventManager.php @@ -109,7 +109,7 @@ public function __call(string $name, array $arguments): void E_USER_DEPRECATED ); if ($name === 'onEveryEvents') { - $this->addGlobalListener($arguments[0], $arguments[1] ?? spl_object_hash($arguments[0])); + $this->addGlobalListener($arguments[0]); } else { $this->addListener(\substr($name, 2), $arguments[0]); } @@ -120,15 +120,10 @@ public function __call(string $name, array $arguments): void /** * @param callable $callback - * @param string $callbackName - * @throws PhpfastcacheEventManagerException */ - public function addGlobalListener(callable $callback, string $callbackName): void + public function addGlobalListener(callable $callback): void { - if (trim($callbackName) === '') { - throw new PhpfastcacheEventManagerException('Parameter $callbackName cannot be empty'); - } - $this->listeners[self::ON_EVERY_EVENT][$callbackName] = $callback; + $this->listeners[self::ON_EVERY_EVENT][] = $callback; } @@ -154,35 +149,20 @@ public function addListener(array|string $events, callable|string $callback): vo } } - /** - * @param string $eventName - * @param string $callbackName - * @return bool - */ - public function unbindEventCallback(string $eventName, string $callbackName): bool - { - $return = isset($this->listeners[$eventName][$callbackName]); - unset($this->listeners[$eventName][$callbackName]); - - return $return; - } - /** * @return bool */ - public function unbindAllEventCallbacks(): bool + public function unbindAllListeners(): void { $this->listeners = [ self::ON_EVERY_EVENT => [] ]; - - return true; } public function __clone(): void { $this->isScopedEventManager = true; - $this->unbindAllEventCallbacks(); + $this->unbindAllListeners(); } /** @@ -209,7 +189,7 @@ public function setItemPoolContext(ExtendedCacheItemPoolInterface $pool): EventM $this->addGlobalListener(static function (EventInterface $event) { self::getInstance()->dispatch($event); - }, 'Scoped' . $pool->getDriverName() . spl_object_hash($this)); + }); return $this; } diff --git a/tests/cases/EventManager.test.php b/tests/cases/EventManager.test.php index 8742e0d0..0d1fe542 100644 --- a/tests/cases/EventManager.test.php +++ b/tests/cases/EventManager.test.php @@ -58,7 +58,7 @@ } $cacheInstance->clear(); unset($item); -$eventInstance->unbindAllEventCallbacks(); +$eventInstance->unbindAllListeners(); $testHelper->debugEvents($eventInstance); $eventInstance->addListener(Events::CACHE_SAVE_MULTIPLE_ITEMS, static function (\Phpfastcache\Event\Event\CacheSaveMultipleItemsItemPoolEvent $event) use ($testHelper) { diff --git a/tests/cases/EventManagerScoped.test.php b/tests/cases/EventManagerScoped.test.php index e3d29058..f5534b6e 100644 --- a/tests/cases/EventManagerScoped.test.php +++ b/tests/cases/EventManagerScoped.test.php @@ -53,7 +53,7 @@ $filesCacheInstance->getEventManager()->addListener(Events::CACHE_GET_ITEM, static function (\Phpfastcache\Event\Event\CacheGetItemEvent $event) use ($testHelper, &$filesGetItemEventManagerCount) { - if($event->getItemPool()->getDriverName() === 'Files') { + if($event->getCachePool()->getDriverName() === 'Files') { $testHelper->assertPass('[Files] Scoped event manager received only events of its own pool instance'); $filesGetItemEventManagerCount++; } @@ -65,7 +65,7 @@ }, 'GlobalEveryEvent'); $redisCacheInstance->getEventManager()->addListener(Events::CACHE_GET_ITEM, static function (\Phpfastcache\Event\Event\CacheGetItemEvent $event) use ($testHelper, &$redisGetItemEventManagerCount) { - if($event->getItemPool()->getDriverName() === 'Redis') { + if($event->getCachePool()->getDriverName() === 'Redis') { $testHelper->assertPass('[Files] Scoped event manager received only events of its own pool instance'); $redisGetItemEventManagerCount++; } From d68849553f79760d354ffd9bfe1f126aa41378cb Mon Sep 17 00:00:00 2001 From: Georges Date: Thu, 1 Feb 2024 00:18:39 +0100 Subject: [PATCH 5/6] Opcache optimization --- docs/EVENTS.md | 2 +- .../Core/Pool/CacheItemPoolTrait.php | 29 ++++++++++--------- .../Core/Pool/DriverBaseTrait.php | 6 ++-- .../Core/Pool/ExtendedCacheItemPoolTrait.php | 4 +-- .../Core/Pool/TaggableCacheItemPoolTrait.php | 2 +- lib/Phpfastcache/Wiki.php | 1 + 6 files changed, 23 insertions(+), 21 deletions(-) diff --git a/docs/EVENTS.md b/docs/EVENTS.md index 99da8ec3..e67a28c4 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -28,7 +28,7 @@ You can simply subscribe to **every** event at once of Phpfastcache. use Phpfastcache\EventManager; EventManager::getInstance()->addGlobalListener(static function (\Phpfastcache\Event\Event\EventInterface $event) { - echo sprintf('Triggered event %s', $event->getName()); + echo sprintf('Triggered event %s', $event::getName()); }); ``` diff --git a/lib/Phpfastcache/Core/Pool/CacheItemPoolTrait.php b/lib/Phpfastcache/Core/Pool/CacheItemPoolTrait.php index d533ac21..2c9f29af 100644 --- a/lib/Phpfastcache/Core/Pool/CacheItemPoolTrait.php +++ b/lib/Phpfastcache/Core/Pool/CacheItemPoolTrait.php @@ -41,6 +41,7 @@ use Phpfastcache\Exceptions\PhpfastcacheIOException; use Phpfastcache\Exceptions\PhpfastcacheLogicException; use Phpfastcache\Exceptions\PhpfastcacheUnsupportedMethodException; +use Phpfastcache\Wiki; use Psr\Cache\CacheItemInterface; use RuntimeException; @@ -132,14 +133,14 @@ public function getItems(array $keys = []): iterable unset($keys[$index]); } } - $keys = array_values($keys); + $keys = \array_values($keys); /** * If there's still keys to fetch, let's choose the right method (if supported). */ - if (count($keys) > 1) { - $items = array_merge( - array_combine($keys, array_map(fn($key) => new (self::getItemClass())($this, $key, $this->eventManager), $keys)), + if (\count($keys) > 1) { + $items = \array_merge( + \array_combine($keys, \array_map(fn($key) => new (self::getItemClass())($this, $key, $this->eventManager), $keys)), $items ); @@ -149,9 +150,9 @@ public function getItems(array $keys = []): iterable /** * Fallback for drivers that does not yet implement driverReadMultiple() method. */ - $driverArrays = array_combine( - array_map(fn($item) => $item->getKey(), $items), - array_map(fn($item) => $this->driverRead($item), $items) + $driverArrays = \array_combine( + \array_map(fn($item) => $item->getKey(), $items), + \array_map(fn($item) => $this->driverRead($item), $items) ); } finally { foreach ($items as $item) { @@ -171,13 +172,13 @@ public function getItems(array $keys = []): iterable $item->setTags($this->driverUnwrapTags($driverArray)); $this->handleExpiredCacheItem($item); } else { - $item->expiresAfter((int) abs($this->getConfig()->getDefaultTtl())); + $item->expiresAfter((int) \abs($this->getConfig()->getDefaultTtl())); } $item->isHit() ? $this->getIO()->incReadHit() : $this->getIO()->incReadMiss(); } } } else { - $index = array_key_first($keys); + $index = \array_key_first($keys); if ($index !== null) { $items[$keys[$index]] = $this->getItem($keys[$index]); } @@ -327,7 +328,7 @@ public function clear(): bool */ public function deleteItems(array $keys): bool { - if (count($keys) > 1) { + if (\count($keys) > 1) { $return = true; try { $items = $this->getItems($keys); @@ -354,7 +355,7 @@ public function deleteItems(array $keys): bool return $return; } - $index = array_key_first($keys); + $index = \array_key_first($keys); if ($index !== null) { return $this->deleteItem($keys[$index]); } @@ -538,7 +539,7 @@ protected function deregisterItem(string $itemKey): static */ protected function deregisterItems(array $itemKeys): static { - $this->itemInstances = array_diff_key($this->itemInstances, array_flip($itemKeys)); + $this->itemInstances = \array_diff_key($this->itemInstances, \array_flip($itemKeys)); if (\gc_enabled()) { \gc_collect_cycles(); @@ -584,7 +585,7 @@ protected function validateCacheKeys(string ...$keys): void if (\preg_match('~([' . \preg_quote(self::$unsupportedKeyChars, '~') . ']+)~', $key, $matches)) { throw new PhpfastcacheInvalidArgumentException( 'Unsupported key character detected: "' . $matches[1] . '". - Please check: https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV6%5D-Unsupported-characters-in-key-identifiers' + Please check: ' . Wiki::UNSUPPORTED_KEY_CHARS ); } } @@ -632,7 +633,7 @@ protected function handleExpiredCacheItem(ExtendedCacheItemInterface $item): voi */ protected function getKeys(array $items, bool $encoded = false, string $keyPrefix = ''): array { - return array_map( + return \array_map( static fn(ExtendedCacheItemInterface $item) => $keyPrefix . ($encoded ? $item->getEncodedKey() : $item->getKey()), $items ); diff --git a/lib/Phpfastcache/Core/Pool/DriverBaseTrait.php b/lib/Phpfastcache/Core/Pool/DriverBaseTrait.php index fc45ffb1..d9a2e083 100644 --- a/lib/Phpfastcache/Core/Pool/DriverBaseTrait.php +++ b/lib/Phpfastcache/Core/Pool/DriverBaseTrait.php @@ -307,13 +307,13 @@ protected function decode(?string $value): ?array { $decoded = $this->unserialize($value); - if ($decoded === null || is_array($decoded)) { + if ($decoded === null || \is_array($decoded)) { return $decoded; } throw new PhpfastcacheCorruptedDataException( - sprintf( + \sprintf( 'Failed to unserialize data from the cache, expected array or null but got "%s". Stored data may be corrupted.', - gettype($decoded) + \gettype($decoded) ), $value ); diff --git a/lib/Phpfastcache/Core/Pool/ExtendedCacheItemPoolTrait.php b/lib/Phpfastcache/Core/Pool/ExtendedCacheItemPoolTrait.php index 725293cd..b871cc0b 100644 --- a/lib/Phpfastcache/Core/Pool/ExtendedCacheItemPoolTrait.php +++ b/lib/Phpfastcache/Core/Pool/ExtendedCacheItemPoolTrait.php @@ -48,8 +48,8 @@ public function getAllItems(string $pattern = ''): iterable $this->eventManager->dispatch(new CacheGetAllItemsEvent($this, new EventReferenceParameter($driverReadAllKeysCallback))); $keys = $driverReadAllKeysCallback($pattern); - if (count($keys) > 0) { - return $this->getItems($keys instanceof \Traversable ? iterator_to_array($keys) : $keys); + if (\count($keys) > 0) { + return $this->getItems($keys instanceof \Traversable ? \iterator_to_array($keys) : $keys); } return []; diff --git a/lib/Phpfastcache/Core/Pool/TaggableCacheItemPoolTrait.php b/lib/Phpfastcache/Core/Pool/TaggableCacheItemPoolTrait.php index 5ae1eb28..b8bfe67c 100644 --- a/lib/Phpfastcache/Core/Pool/TaggableCacheItemPoolTrait.php +++ b/lib/Phpfastcache/Core/Pool/TaggableCacheItemPoolTrait.php @@ -446,7 +446,7 @@ protected function driverWriteTags(ExtendedCacheItemInterface $item): bool * then remove it from tagsItems index */ if (\count($data)) { - $tagsItem->expiresAt((new DateTime())->setTimestamp(max($data))); + $tagsItem->expiresAt((new DateTime())->setTimestamp(\max($data))); $this->driverWrite($tagsItem); $tagsItem->setHit(true); } else { diff --git a/lib/Phpfastcache/Wiki.php b/lib/Phpfastcache/Wiki.php index 060d15c8..b4831172 100644 --- a/lib/Phpfastcache/Wiki.php +++ b/lib/Phpfastcache/Wiki.php @@ -23,4 +23,5 @@ class Wiki use UninstanciableObjectTrait; public const FETCH_ALL_KEY_URL = 'https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV5%CB%96%5D-Fetching-all-keys'; + public const UNSUPPORTED_KEY_CHARS = 'https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV6%5D-Unsupported-characters-in-key-identifiers'; } From 4cafdf13dec20442ff051f768377742a45af4258 Mon Sep 17 00:00:00 2001 From: Georges Date: Fri, 2 Feb 2024 22:56:40 +0100 Subject: [PATCH 6/6] GC optimization --- .../Core/Pool/CacheItemPoolTrait.php | 20 +++++++++++++------ .../Core/Pool/ExtendedCacheItemPoolTrait.php | 6 +----- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/lib/Phpfastcache/Core/Pool/CacheItemPoolTrait.php b/lib/Phpfastcache/Core/Pool/CacheItemPoolTrait.php index 2c9f29af..ffe06b68 100644 --- a/lib/Phpfastcache/Core/Pool/CacheItemPoolTrait.php +++ b/lib/Phpfastcache/Core/Pool/CacheItemPoolTrait.php @@ -31,13 +31,11 @@ use Phpfastcache\Event\Event\CacheItemPoolEventGetItems; use Phpfastcache\Event\Event\CacheSaveDeferredItemItemPoolEvent; use Phpfastcache\Event\Event\CacheItemPoolEventSaveItem; -use Phpfastcache\Event\Events; use Phpfastcache\Event\EventManagerInterface; use Phpfastcache\Event\EventReferenceParameter; use Phpfastcache\Exceptions\PhpfastcacheCoreException; use Phpfastcache\Exceptions\PhpfastcacheDriverException; use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException; -use Phpfastcache\Exceptions\PhpfastcacheInvalidTypeException; use Phpfastcache\Exceptions\PhpfastcacheIOException; use Phpfastcache\Exceptions\PhpfastcacheLogicException; use Phpfastcache\Exceptions\PhpfastcacheUnsupportedMethodException; @@ -113,6 +111,7 @@ public function setItem(CacheItemInterface $item): static */ public function getItems(array $keys = []): iterable { + $gcStatus = gc_enabled(); $items = []; $config = $this->getConfig(); @@ -139,6 +138,9 @@ public function getItems(array $keys = []): iterable * If there's still keys to fetch, let's choose the right method (if supported). */ if (\count($keys) > 1) { + if ($gcStatus) { + gc_disable(); + } $items = \array_merge( \array_combine($keys, \array_map(fn($key) => new (self::getItemClass())($this, $key, $this->eventManager), $keys)), $items @@ -176,6 +178,9 @@ public function getItems(array $keys = []): iterable } $item->isHit() ? $this->getIO()->incReadHit() : $this->getIO()->incReadMiss(); } + if ($gcStatus) { + gc_enable(); + } } } else { $index = \array_key_first($keys); @@ -204,7 +209,6 @@ public function getItems(array $keys = []): iterable * @throws PhpfastcacheCoreException * @throws PhpfastcacheInvalidArgumentException * @throws PhpfastcacheLogicException - * @throws PhpfastcacheDriverException * * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.GotoStatement) @@ -534,12 +538,16 @@ protected function deregisterItem(string $itemKey): static } /** - * @param string[] $itemKeys + * @param ?string[] $itemKeys * @internal This method de-register multiple items from $this->itemInstances */ - protected function deregisterItems(array $itemKeys): static + protected function deregisterItems(?array $itemKeys): static { - $this->itemInstances = \array_diff_key($this->itemInstances, \array_flip($itemKeys)); + if ($itemKeys !== null) { + $this->itemInstances = \array_diff_key($this->itemInstances, \array_flip($itemKeys)); + } else { + $this->itemInstances = []; + } if (\gc_enabled()) { \gc_collect_cycles(); diff --git a/lib/Phpfastcache/Core/Pool/ExtendedCacheItemPoolTrait.php b/lib/Phpfastcache/Core/Pool/ExtendedCacheItemPoolTrait.php index b871cc0b..05398650 100644 --- a/lib/Phpfastcache/Core/Pool/ExtendedCacheItemPoolTrait.php +++ b/lib/Phpfastcache/Core/Pool/ExtendedCacheItemPoolTrait.php @@ -76,11 +76,7 @@ public function getItemsAsJsonString(array $keys = [], int $options = \JSON_THRO public function detachAllItems(): static { - foreach ($this->itemInstances as $item) { - $this->detachItem($item); - } - - return $this; + return $this->deregisterItems(null); } public function detachItem(CacheItemInterface $item): static