Skip to content

Commit c3ba10c

Browse files
committed
Improved EventManager code
1 parent 51468fa commit c3ba10c

24 files changed

+337
-173
lines changed

CHANGELOG.md

+6-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
## 9.0.0
2-
##### 1 november 2021
2+
##### 1 october 2021
33
- __Migration guide__
44
- Read the [migration guide](./docs/migration/MigratingFromV8ToV9.md) to upgrade from V8 to V9
55
- __API__
@@ -9,6 +9,8 @@
99
- Renamed `Api::getPhpFastCacheGitHeadHash()` to `Api::getPhpfastcacheGitHeadHash()`
1010
- __Cluster__
1111
- Renamed `\Phpfastcache\Cluster\AggregatorInterface::aggregateNewDriver()` to `\Phpfastcache\Cluster\AggregatorInterface::aggregateDriverByName()`
12+
- __Exceptions__
13+
- Added `PhpfastcacheEventManagerException` for EventManager-related exceptions
1214
- __Global__
1315
- Removed magics methods from CacheManager `CacheManager::DriverName()`, use `CacheManager::getInstance('DriverName')` instead
1416
- Slightly increased performances on some critical points of the library
@@ -45,7 +47,9 @@
4547
- Added `Devrandom` with configurable factor chance and data length
4648
- Renamed classes `\Phpfastcache\Cluster\Drivers\[STATEGY]\[CLUSTER_NAME]Cluster` to `\Phpfastcache\Cluster\Drivers\[STATEGY]\Driver` for better driver naming across the project
4749
- __Events__
48-
- Added `\Phpfastcache\Event\EventReferenceParameter` class, see [EVENTS.md](./docs/EVENTS.md) file for more information
50+
- Added `\Phpfastcache\Event\EventReferenceParameter` class and more events such as driver-specific events, see [EVENTS.md](./docs/EVENTS.md) file for more information
51+
- Event callbacks will now receive the `eventName` as an extra _last_ callback parameter (except for `onEveryEvents` callbacks)
52+
- Added `EventManagerInterface::on(array $eventNames, $callback)` method, to subscribe to multiple events in once with the same callback
4953
- Added method named `unbindAllEventCallbacks(): bool` to `EventManagerInterface` to allow you to unbind/clear all event from an event instance
5054
- Updated argument type #2 (`$items`) of `onCacheSaveMultipleItems()` event from `ExtendedCacheItemInterface[]` to `EventReferenceParameter($items)`
5155
- Updated argument type #2 (`$items`) of `onCacheCommitItem()` event from `ExtendedCacheItemInterface[]` to `EventReferenceParameter($items)`

docs/EVENTS.md

+54-15
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,31 @@ EventManager::getInstance()->unbindEventCallback('onCacheGetItem', 'myCallbackNa
3434

3535
```
3636

37-
:new: In V9 some callback parameter, that aren't objects, are passed by reference via the new `\Phpfastcache\Event\EventReferenceParameter` class.\
38-
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.\
39-
If it's allowed by the event dispatcher the type can be changed or not.\
40-
If you try to while it's not allowed, you will get a `PhpfastcacheInvalidArgumentException` when trying to call `\Phpfastcache\Event\EventReferenceParameter::setParameterValue()`\
41-
Finally the class `\Phpfastcache\Event\EventReferenceParameter` is `invokable` and trying to do so will return you the parameter value.\
37+
:new: in V8
4238

43-
:new: In V9, a method named `unbindAllEventCallbacks(): bool` has been added to `EventManagerInterface` to allow you to unbind/clear all event from an event instance.
39+
You can simply subscribe to **every** events at once of Phpfastcache.
40+
```php
41+
<?php
42+
use Phpfastcache\EventManager;
43+
44+
EventManager::getInstance()->onEveryEvents(static function (string $eventName, ...$args) {
45+
echo sprintf("Triggered event '{$eventName}' with %d arguments provided", count($args));
46+
}, 'debugCallback');
47+
```
48+
49+
This is an exhaustive list, and it will be updated as soon as new events will be added to the Core.
50+
51+
52+
:new: In V9
53+
54+
- Some callback parameter, that are __NOT__ objects, are passed by reference via the new `\Phpfastcache\Event\EventReferenceParameter` class.\
55+
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.\
56+
If it's allowed by the event dispatcher the type can be changed or not.\
57+
If you try to while it's not allowed, you will get a `PhpfastcacheInvalidArgumentException` when trying to call `\Phpfastcache\Event\EventReferenceParameter::setParameterValue()`\
58+
Finally the class `\Phpfastcache\Event\EventReferenceParameter` is `invokable` and trying to do so will return you the parameter value.\
59+
- A method named `unbindAllEventCallbacks(): bool` has been added to `EventManagerInterface` to allow you to unbind/clear all event from an event instance.
60+
- Event callbacks will now receive the `eventName` as an extra _last_ callback parameter (except for `onEveryEvents` callbacks)
61+
- Added `EventManagerInterface::on(array $eventNames, $callback)` method, to subscribe to multiple events in once with the same callback
4462

4563
## List of active events:
4664
### ItemPool Events
@@ -226,14 +244,35 @@ Finally the class `\Phpfastcache\Event\EventReferenceParameter` is `invokable` a
226244
- **Risky Circular Methods**
227245
- *ExtendedCacheItemInterface::expiresAt()*
228246

229-
:new: As of the **V8** you can simply subscribe to **every** events at once of Phpfastcache.
230-
```php
231-
<?php
232-
use Phpfastcache\EventManager;
247+
### Driver-specific Events (as of V9)
248+
#### Arangodb
249+
- onArangodbConnection(*Callable* **$callback**)
250+
- **Callback arguments**
251+
- *ExtendedCacheItemPoolInterface* **$itemPool**
252+
- *EventReferenceParameter($connectionOptions)* **$connectionOptions** _via EventReferenceParameter object_ **(type modification forbidden)**
253+
- **Scope**
254+
- Arangodb Driver
255+
- **Description**
256+
- Allow you to alter the parameters built used to connect to Arangodb server
257+
- **Risky Circular Methods**: None
233258

234-
EventManager::getInstance()->onEveryEvents(static function (string $eventName, ...$args) {
235-
echo sprintf("Triggered event '{$eventName}' with %d arguments provided", count($args));
236-
}, 'debugCallback');
237-
```
259+
- onArangodbCollectionParams(*Callable* **$callback**)
260+
- **Callback arguments**
261+
- *ExtendedCacheItemPoolInterface* **$itemPool**
262+
- *EventReferenceParameter($params)* **$params** _via EventReferenceParameter object_ **(type modification forbidden)**
263+
- **Scope**
264+
- Arangodb Driver
265+
- **Description**
266+
- Allow you to alter the parameters built used to create the collection
267+
- **Risky Circular Methods**: None
238268

239-
This is an exhaustive list and it will be updated as soon as new events will be added to the Core.
269+
#### Dynamodb
270+
- onDynamodbCreateTable(*Callable* **$callback**)
271+
- **Callback arguments**
272+
- *ExtendedCacheItemPoolInterface* **$itemPool**
273+
- *EventReferenceParameter($params)* **$params** _via EventReferenceParameter object_ **(type modification forbidden)**
274+
- **Scope**
275+
- Dynamodb Driver
276+
- **Description**
277+
- Allow you to alter the parameters built used to create the table
278+
- **Risky Circular Methods**: None

lib/Phpfastcache/CacheManager.php

+5-2
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,11 @@ public static function getInstance(string $driver, ?ConfigurationOptionInterface
108108
if ($configClass !== $config::class) {
109109
$config = new $configClass($config->toArray());
110110
}
111-
self::$instances[$instanceId] = new $driverClass($config, $instanceId);
112-
self::$instances[$instanceId]->setEventManager(EventManager::getInstance());
111+
self::$instances[$instanceId] = new $driverClass(
112+
$config,
113+
$instanceId,
114+
EventManager::getInstance()
115+
);
113116
} else {
114117
throw new PhpfastcacheDriverNotFoundException(sprintf('The driver "%s" does not exists', $driver));
115118
}

lib/Phpfastcache/Cluster/ClusterAggregator.php

+2
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use Exception;
1919
use Phpfastcache\CacheManager;
2020
use Phpfastcache\Config\ConfigurationOption;
21+
use Phpfastcache\EventManager;
2122
use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException;
2223
use Phpfastcache\Exceptions\PhpfastcacheDriverException;
2324
use Phpfastcache\Exceptions\PhpfastcacheDriverNotFoundException;
@@ -144,6 +145,7 @@ public function getCluster(int $strategy = AggregatorInterface::STRATEGY_FULL_RE
144145
$clusterClass = ClusterPoolAbstract::STRATEGY[$strategy];
145146
$this->cluster = new $clusterClass(
146147
$this->getClusterAggregatorName(),
148+
EventManager::getInstance(),
147149
...\array_values($this->driverPools)
148150
);
149151

lib/Phpfastcache/Cluster/ClusterPoolAbstract.php

+5-3
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait;
2626
use Phpfastcache\Entities\DriverIO;
2727
use Phpfastcache\Entities\DriverStatistic;
28+
use Phpfastcache\Event\EventManagerInterface;
2829
use Phpfastcache\EventManager;
2930
use Phpfastcache\Exceptions\PhpfastcacheCoreException;
3031
use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException;
@@ -61,6 +62,7 @@ abstract class ClusterPoolAbstract implements ClusterPoolInterface
6162
/**
6263
* ClusterPoolAbstract constructor.
6364
* @param string $clusterName
65+
* @param EventManagerInterface $em
6466
* @param ExtendedCacheItemPoolInterface ...$driverPools
6567
* @throws PhpfastcacheDriverCheckException
6668
* @throws PhpfastcacheDriverConnectException
@@ -69,13 +71,13 @@ abstract class ClusterPoolAbstract implements ClusterPoolInterface
6971
* @throws PhpfastcacheDriverException
7072
* @throws PhpfastcacheIOException
7173
*/
72-
public function __construct(string $clusterName, ExtendedCacheItemPoolInterface ...$driverPools)
74+
public function __construct(string $clusterName, EventManagerInterface $em, ExtendedCacheItemPoolInterface ...$driverPools)
7375
{
7476
if (count($driverPools) < 2) {
7577
throw new PhpfastcacheInvalidArgumentException('A cluster requires at least two pools to be working.');
7678
}
7779
$this->clusterPools = $driverPools;
78-
$this->__parentConstruct(new ConfigurationOption(), $clusterName);
80+
$this->__parentConstruct(new ConfigurationOption(), $clusterName, $em);
7981
$this->setEventManager(EventManager::getInstance());
8082
}
8183

@@ -183,7 +185,7 @@ protected function getStandardizedItem(ExtendedCacheItemInterface $item, Extende
183185
if ($driverPool === $this) {
184186
/** @var ExtendedCacheItemInterface $itemPool */
185187
$itemClass = $driverPool->getItemClass();
186-
$itemPool = new $itemClass($this, $item->getKey());
188+
$itemPool = new $itemClass($this, $item->getKey(), $this->getEventManager());
187189

188190
$this->remapCacheItem($item, $itemPool, $driverPool);
189191

lib/Phpfastcache/Cluster/Drivers/FullReplication/Driver.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ public function getItem(string $key): ExtendedCacheItemInterface
7272
}
7373
}
7474

75-
return $this->getStandardizedItem($item ?? new Item($this, $key), $this);
75+
return $this->getStandardizedItem($item ?? new Item($this, $key, $this->getEventManager()), $this);
7676
}
7777

7878
/**

lib/Phpfastcache/Cluster/Drivers/MasterSlaveReplication/Driver.php

+12-6
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,15 @@
1818
use Phpfastcache\Cluster\ClusterPoolAbstract;
1919
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
2020
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
21+
use Phpfastcache\EventManager;
22+
use Phpfastcache\Exceptions\PhpfastcacheCoreException;
2123
use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException;
2224
use Phpfastcache\Exceptions\PhpfastcacheDriverConnectException;
25+
use Phpfastcache\Exceptions\PhpfastcacheDriverException;
2326
use Phpfastcache\Exceptions\PhpfastcacheExceptionInterface;
2427
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
2528
use Phpfastcache\Exceptions\PhpfastcacheInvalidConfigurationException;
29+
use Phpfastcache\Exceptions\PhpfastcacheIOException;
2630
use Phpfastcache\Exceptions\PhpfastcacheReplicationException;
2731
use Psr\Cache\CacheItemInterface;
2832
use ReflectionException;
@@ -32,20 +36,22 @@ class Driver extends ClusterPoolAbstract
3236
/**
3337
* MasterSlaveReplicationCluster constructor.
3438
* @param string $clusterName
39+
* @param EventManager $em
3540
* @param ExtendedCacheItemPoolInterface ...$driverPools
36-
* @throws PhpfastcacheInvalidArgumentException
3741
* @throws PhpfastcacheDriverCheckException
3842
* @throws PhpfastcacheDriverConnectException
39-
* @throws PhpfastcacheInvalidConfigurationException
40-
* @throws ReflectionException
43+
* @throws PhpfastcacheInvalidArgumentException
44+
* @throws PhpfastcacheCoreException
45+
* @throws PhpfastcacheDriverException
46+
* @throws PhpfastcacheIOException
4147
*/
42-
public function __construct(string $clusterName, ExtendedCacheItemPoolInterface ...$driverPools)
48+
public function __construct(string $clusterName, EventManager $em, ExtendedCacheItemPoolInterface ...$driverPools)
4349
{
4450
if (\count($driverPools) !== 2) {
4551
throw new PhpfastcacheInvalidArgumentException('A "master/slave" cluster requires exactly two pools to be working.');
4652
}
4753

48-
parent::__construct($clusterName, ...$driverPools);
54+
parent::__construct($clusterName, $em, ...$driverPools);
4955
}
5056

5157
/**
@@ -54,7 +60,7 @@ public function __construct(string $clusterName, ExtendedCacheItemPoolInterface
5460
public function getItem(string $key): ExtendedCacheItemInterface
5561
{
5662
return $this->getStandardizedItem(
57-
$this->makeOperation(static fn (ExtendedCacheItemPoolInterface $pool) => $pool->getItem($key)) ?? new Item($this, $key),
63+
$this->makeOperation(static fn (ExtendedCacheItemPoolInterface $pool) => $pool->getItem($key)) ?? new Item($this, $key, $this->getEventManager()),
5864
$this
5965
);
6066
}

lib/Phpfastcache/Cluster/Drivers/RandomReplication/Driver.php

+3-2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
use Phpfastcache\Cluster\Drivers\MasterSlaveReplication\Driver as MasterSlaveReplicationDriver;
1919
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
20+
use Phpfastcache\Event\EventManagerInterface;
2021
use ReflectionException;
2122
use ReflectionMethod;
2223

@@ -28,10 +29,10 @@ class Driver extends MasterSlaveReplicationDriver
2829
* @param ExtendedCacheItemPoolInterface ...$driverPools
2930
* @throws ReflectionException
3031
*/
31-
public function __construct(string $clusterName, ExtendedCacheItemPoolInterface ...$driverPools)
32+
public function __construct(string $clusterName, EventManagerInterface $em, ExtendedCacheItemPoolInterface ...$driverPools)
3233
{
3334
(new ReflectionMethod(\get_parent_class(\get_parent_class($this)), __FUNCTION__))
34-
->invoke($this, $clusterName, ...$driverPools);
35+
->invoke($this, $clusterName, $em, ...$driverPools);
3536
$randomPool = $driverPools[\random_int(0, \count($driverPools) - 1)];
3637

3738
$this->eventManager->dispatch(

lib/Phpfastcache/Cluster/Drivers/SemiReplication/Driver.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public function getItem(string $key): ExtendedCacheItemInterface
5151
throw new PhpfastcacheReplicationException('Every pools thrown an exception');
5252
}
5353

54-
return $this->getStandardizedItem($item ?? new Item($this, $key), $this);
54+
return $this->getStandardizedItem($item ?? new Item($this, $key, $this->getEventManager()), $this);
5555
}
5656

5757
/**

lib/Phpfastcache/Core/Item/ExtendedCacheItemTrait.php

+4-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use DateTime;
1919
use DateTimeInterface;
2020
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
21+
use Phpfastcache\Event\EventManagerInterface;
2122
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
2223
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
2324
use Phpfastcache\Util\ClassNamespaceResolverTrait;
@@ -34,12 +35,14 @@ trait ExtendedCacheItemTrait
3435
* Item constructor.
3536
* @param ExtendedCacheItemPoolInterface $driver
3637
* @param string $key
38+
* @param EventManagerInterface $em
3739
* @throws PhpfastcacheInvalidArgumentException
3840
*/
39-
public function __construct(ExtendedCacheItemPoolInterface $driver, string $key)
41+
public function __construct(ExtendedCacheItemPoolInterface $driver, string $key, EventManagerInterface $em)
4042
{
4143
$this->data = null;
4244
$this->key = $key;
45+
$this->setEventManager($em);
4346
$this->setDriver($driver);
4447
if ($driver->getConfig()->isUseStaticItemCaching()) {
4548
$this->driver->setItem($this);

lib/Phpfastcache/Core/Pool/CacheItemPoolTrait.php

+5-8
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@
3434

3535
trait CacheItemPoolTrait
3636
{
37-
use EventManagerDispatcherTrait;
3837
use DriverBaseTrait;
3938

4039
/**
@@ -128,8 +127,7 @@ public function getItem(string $key): ExtendedCacheItemInterface
128127
$cacheSlamsSpendSeconds = 0;
129128
$itemClass = self::getItemClass();
130129
/** @var $item ExtendedCacheItemInterface */
131-
$item = new $itemClass($this, $key);
132-
$item->setEventManager($this->eventManager);
130+
$item = new $itemClass($this, $key, $this->eventManager);
133131

134132
getItemDriverRead:
135133
{
@@ -405,9 +403,9 @@ public function commit(): bool
405403
* @return bool
406404
* @throws PhpfastcacheCoreException
407405
* @throws PhpfastcacheDriverException
406+
* @throws PhpfastcacheIOException
408407
* @throws PhpfastcacheInvalidArgumentException
409408
* @throws PhpfastcacheLogicException
410-
* @throws \ReflectionException
411409
*/
412410
public function save(CacheItemInterface $item): bool
413411
{
@@ -438,10 +436,9 @@ public function save(CacheItemInterface $item): bool
438436
/**
439437
* @var $itemBatch ExtendedCacheItemInterface
440438
*/
441-
$class = new ReflectionClass((new ReflectionObject($this))->getNamespaceName() . '\Item');
442-
$itemBatch = $class->newInstanceArgs([$this, $item->getKey()]);
443-
$itemBatch->setEventManager($this->eventManager)
444-
->set(new ItemBatch($item->getKey(), new DateTime()))
439+
$itemClassName = self::getItemClass();
440+
$itemBatch = new $itemClassName($this, $item->getKey(), $this->eventManager);
441+
$itemBatch->set(new ItemBatch($item->getKey(), new DateTime()))
445442
->expiresAfter($this->getConfig()->getCacheSlamsTimeout());
446443

447444
/**

lib/Phpfastcache/Core/Pool/DriverBaseTrait.php

+6-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
use DateTime;
1919
use DateTimeInterface;
2020
use Phpfastcache\Config\ConfigurationOptionInterface;
21+
use Phpfastcache\Event\EventManagerDispatcherTrait;
22+
use Phpfastcache\Event\EventManagerInterface;
2123
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
2224
use Phpfastcache\Util\ClassNamespaceResolverTrait;
2325
use Throwable;
@@ -35,6 +37,7 @@ trait DriverBaseTrait
3537
{
3638
use DriverPoolAbstractTrait;
3739
use ClassNamespaceResolverTrait;
40+
use EventManagerDispatcherTrait;
3841

3942
protected static array $cacheItemClasses = [];
4043

@@ -50,14 +53,16 @@ trait DriverBaseTrait
5053
* Driver constructor.
5154
* @param ConfigurationOptionInterface $config
5255
* @param string $instanceId
56+
* @param EventManagerInterface $em
5357
* @throws PhpfastcacheCoreException
5458
* @throws PhpfastcacheDriverCheckException
5559
* @throws PhpfastcacheDriverConnectException
5660
* @throws PhpfastcacheIOException
5761
* @throws PhpfastcacheInvalidArgumentException
5862
*/
59-
public function __construct(ConfigurationOptionInterface $config, string $instanceId)
63+
public function __construct(ConfigurationOptionInterface $config, string $instanceId, EventManagerInterface $em)
6064
{
65+
$this->setEventManager($em);
6166
$this->setConfig($config);
6267
$this->instanceId = $instanceId;
6368
$this->IO = new DriverIO();

0 commit comments

Comments
 (0)