judahnator/mirror

Mirror for PHP objects and arrays

v1.0.0 2020-09-22 10:07 UTC

This package is not auto-updated.

Last update: 2024-04-18 09:00:24 UTC


README

I'll preface with this:

  • If you think you need this, you don't.
  • If you know you need this, you already know that you shouldn't use it.

With that out of the way, what is this? This is a shim that allows you to return a concrete object that would otherwise need to be a reference. This can be handy if you are trying to provide a transparent getter/setter interface with an interface with another data type.

By doing this you can interact with a concrete object as if you would a normal object or list, and have the changes reflected back on the original input.

Examples

Lists:

$foods = ['Apples', 'Bananas', 'Celery'];
$mirror = \judahnator\Mirror\MirrorType::of($foods);

$mirror[] = 'Cake'; // Everybody likes cake
unset($mirror[2]); // Nobody likes celery

// ["Apples","Bananas","Cake"]
print_r($foods);

Objects:

$weather = json_decode('{"skies": "cloudy", "rain": true}');
$mirror = \judahnator\Mirror\MirrorType::of($weather);

$mirror->skies = 'clear';
$mirror->rain = false;
$mirror->temp = 72;

// (object)['skies' => 'clear', 'rain' => false, 'temp' => 72]
print_r($weather);