gitmyhub

DeepCopy

PHP ★ 8.9k updated 5mo ago

Create deep copies (clones) of your objects

A PHP library that creates fully independent copies of complex objects, including ones with circular references, so modifying the copy never accidentally changes the original.

PHPComposersetup: easycomplexity 2/5

DeepCopy is a PHP library that creates full, independent copies of objects, including all the objects they reference internally. In programming, when you copy an object with PHP's built-in clone command, only the top-level object is duplicated. Any nested objects it points to still refer to the same underlying data, which can cause unexpected behavior when you modify the copy. DeepCopy solves this by walking through all of an object's properties recursively and duplicating each one.

A particular challenge it addresses is circular references, where object A references object B, which in turn references object A. Naive deep copy approaches can get stuck in an infinite loop or create duplicate copies of the same object. DeepCopy tracks which objects have already been cloned and reuses those copies, preserving the original structure without getting caught in loops.

The library also allows you to customize the copy process using filters and matchers. A matcher identifies which properties or types to target, and a filter describes what to do with them. For example, you can tell DeepCopy to set a property named "id" to null in the copy (useful when duplicating a database record that should get a new identifier), or to leave a particular property untouched rather than copying it. Several built-in filters handle common cases when working with Doctrine, a popular PHP database library.

Installation is done through Composer, the standard PHP package manager, with a single command. The basic usage is straightforward: create a DeepCopy instance and call its copy method with the object you want to duplicate. The library is installed automatically when you use PHPUnit, a widely used PHP testing framework, which partly explains its high download count.

Where it fits