upscale/stdlib-object-lifecycle

Library to monitor lifecycle of objects allocated by long-running PHP scripts

2.0.3 2019-09-02 06:21 UTC

This package is auto-updated.

Last update: 2024-04-18 06:17:55 UTC


README

This library tracks existence of objects throughout their lifecycle until eventual destruction. It can accurately detect memory leaks in long-running CLI scripts or event-driven web-servers, such as Swoole or ReactPHP.

The monitoring can be easily activated for applications with centralized object instantiation, i.e. using a DI container.

Features:

  • Watch any object w/o modifying its source code
  • Detect objects that are still alive
  • Detect objects that have been destroyed
  • Debug info on alive/destroyed objects: class, hash, trace
  • Garbage collection of circular references

Installation

The library is to be installed via Composer as a dependency:

composer require upscale/stdlib-object-lifecycle

Usage

Detect destruction of objects:

$obj1 = new \stdClass();
$obj2 = new \stdClass();
$obj3 = new \stdClass();

// Circular references subject to garbage collection
$obj1->ref = $obj2;
$obj2->ref = $obj1;

$watcher = new \Upscale\Stdlib\Object\Lifecycle\Watcher();
$watcher->watch($obj1);
$watcher->watch([$obj2, $obj3]);

unset($obj1);

// Outputs 3 because of circular references
echo count($watcher->detectAliveObjects());

unset($obj2);

// Outputs 3 because of pending garbage collection 
echo count($watcher->detectAliveObjects(false));

// Outputs 1 after forced garbage collection 
echo count($watcher->detectAliveObjects());

unset($obj3);

// Outputs 0 and 3 respectively
echo count($watcher->detectAliveObjects());
echo count($watcher->detectGoneObjects());

Methods detectAliveObjects() and detectGoneObjects() return the following debug information:

array(
  array(
    'type' => 'stdClass',
    'hash' => '00000000524c32e1000000002cee0034',
    'trace' => '#0 demo.php(26): Upscale\\Stdlib\\Object\\Lifecycle\\Watcher->watch(Object(stdClass))
#1 demo.php(10): Example->runTest()
#2 demo.php(53): Example->test()
#3 {main}',
  ),
  ...
)

Contributing

Pull Requests with fixes and improvements are welcome!

License

Licensed under the Apache License, Version 2.0.