moirei/objects

Simple data & array objects.

1.1.0 2023-07-14 11:53 UTC

This package is auto-updated.

Last update: 2024-04-14 13:30:34 UTC


README

A package for simple and lightweight data/array objects.

Install

composer require moirei/objects

Note: this package does not automatically cast nested objects.

Usage

Object

final class User extends BaseObject
{
  public string $name;
  public string $email;
}
$user = new User([
  'name' => 'Joe',
  'email' => 'top_lad@mail.com',
]);

// or

$user = User::make([
  'name' => 'Joe',
  'email' => 'top_lad@mail.com',
]);

// or

$user = User::make();
$user->name = 'Joe';
$user['email'] = 'top_lad@mail.com';

...

dump($user->toArray());
dump($user);

Accessing or mutation undefined properties throws an exception.

Non-strict Object

/**
 * @property string|null $city
 */
final class User extends BaseObject
{
  protected $strict = false;
  public string $name;
  public string $email;
}
$user = User::make([
  'name' => 'Joe',
  'email' => 'top_lad@mail.com',
]);

...
$user->city = 'Adelaide';

Accessing or mutation undefined properties is allowed.

Rationale

If you're no longer comfortable passing or returning data as untyped array to your app logic, and want a simple solution, then this package is for you.

For the below example, we can be confident of the data type being returned from the action.

final class InstallationStatus extends BaseObject
{
    public bool $completed = false;
    public ?string $key;
    /** @var string[] */
    public array $errors = [];
}
class InstallAppAction{
  use AsAction;

  public function handle(string $code): InstallationStatus{
    $status = InstallationStatus::make();

    try{
      // logic
      $status->completed = true;
      $status->key = '...';
    }catch(\Exception $e){
      $status->errors = [
        $e->getMessage()
      ];
    }

    return $status;
  }
}

License

MIT

Special thanks to Eduardo San Martin Morote (posva) for encoding utlities