phasync / objectpool
一个实现高效对象池的库。
dev-main
2024-06-11 07:37 UTC
This package is auto-updated.
Last update: 2024-09-11 08:15:15 UTC
README
一个用于PHP对象的效率对象池实现。
示例
对于任何可以从对象池中受益的类
class Vector implements phasync\Util\ObjectPoolInterface { use phasync\Util\ObjectPoolTrait; public string $name; public ?PDO $dbConnection; /** * Instead of creating instances via the constructor, instances must be * created via a static method (such as this `create()` function). */ public static function create(string $name, PDO $dbConnection): static { $instance = static::popInstance() ?? new static(); $instance->name = $name; $instance->dbConnection = $dbConnection; } /** * The constructor MUST be declared as private or protected, to ensure * you don't leak memory by adding an infinite number of instances to * the pool without ever recovering them. */ private function __construct() {} /** * This function is used to return the instance to the object pool. * The function must ensure that a clean object is returned to the * object pool, removing any non-scalar values - even if the properties * would be overwritten when retrieved. This is to avoid memory leaks. */ public function returnToPool(): void { /** * It is ESSENTIAL to unset references to values such as * `$this->dbInstance` before returning the object to the pool. */ $this->name = ''; $this->dbConnection = null; $this->pushInstance(); } }
警告
仅使用此功能对内部对象,这些对象在代码中使用频繁,且其他开发者不直接与之交互。这是确保在将对象返回池中时没有剩余引用的唯一方法。你必须避免开发者在将实例添加到对象池时保留对其实例的引用。