vectorial1024/multiton-dto

Ergonomic PHP library for optimizing data transfer objects (DTOs).

dev-master 2025-01-27 10:10 UTC

This package is auto-updated.

Last update: 2025-01-27 10:11:03 UTC


README

Packagist License Packagist Version Packagist Downloads PHP Dependency Version GitHub Actions Workflow Status GitHub Repo Stars

Ergonomic PHP library for optimizing data transfer objects (DTOs).

Situation / Why should I need this?

Data transfer objects (DTOs) in PHP are very minimal classes that has the only objective of representing a piece of data for easy data transfer. In modern PHP, they can be classes with only readonly properties.

DTOs are great, but when readonly DTOs need to be (re)created many times, problems may arise. Consider:

// create instance for usage...
$dto = new ReadOnlyDto(1);

// ...
// somewhere else unrelated
$anotherDto = new ReadOnlyDto(1);

// ...

Here, $dto and $anotherDto are two different object instances; $dto == $anotherDto but $dto !== $anotherDto. This means:

  • Unnecessarily high overall memory usage for such readonly DTOs, esp. when needing to duplicate them many times
    • An example could be the result dataset of a database JOIN query
  • Impossible to use with e.g. WeakMap, which relies on the specific object instances

With this ergonomic library, same readonly DTO instances can be conveniently deduplicated, so that e.g. memory usage may be minimized. This is an example of the multiton pattern where multiple DTO instances are allowed to exist only if their identities are distinct.

Note that this library is flexible: it will only activate when explicitly requested by the user. In case the DTOs will never duplicate (e.g. RESTful API returning a single instance to the caller), simply don't invoke this library and this library will get out of the way.

Consider this library as a loose analog of e.g. C#'s struct datatype.

Installation

via Composer:

composer require vectorial1024/multiton-dto

Usage

(WIP)

Testing

(WIP)