simplecomplex/explorable

Foreach'ing protected members made simple

1.0.0 2021-04-19 06:16 UTC

This package is auto-updated.

Last update: 2024-04-19 17:16:18 UTC


README

composer namespace: simplecomplex/explorable

Foreach'ing protected members made simple

An interface, base class and traits making it a breeze to expose a class' protected members.

Extending Explorable facilitates:

  • isset()
  • count()
  • foreach (...
  • var_dump()
  • toObject(), toArray()
  • json_encode()

Usage

Class declaring it's properties

Property names hardcoded in constant EXPLORABLE_VISIBLE.

<?php

use SimpleComplex\Explorable\Explorable;
use SimpleComplex\Explorable\ExplorableTrait;

/**
 * @property-read string $foo
 * @property-read string $bar
 */
class ExplorablesDeclared extends Explorable
{
    use ExplorableTrait;

    public const EXPLORABLE_VISIBLE = [
        'foo' => true,
        'bar' => true,
    ];

    protected string $foo;

    protected string $bar;
}

Class relying on property table discovery

The properties will be discovered on-demand, via explorablePrepare().

All instance vars must be nullable and declared as null (protected ?string $foo = null;).
Otherwise risk of getting "::$foo must not be accessed before initialization" error, or the instance vars simply won't get discovered (because not set to a value (null)).

<?php

use SimpleComplex\Explorable\Explorable;
use SimpleComplex\Explorable\ExplorableTrait;

/**
 * @property-read string $foo
 * @property-read string $bar
 */
class ExplorablesDiscoverable extends Explorable
{
    use ExplorableTrait;

    protected ?string $foo = null;

    protected ?string $bar = null;
}

MIT licensed

License and copyright. Explained.

Requirements

  • PHP ^7.4 || ^8.0

Development (require-dev)

  • phpunit ^8 || ^9