moirei / objects
Simple data & array objects.
1.1.0
2023-07-14 11:53 UTC
Requires
- php: ^8.0
- illuminate/support: ^8|^9|^10.0
Requires (Dev)
- laravel/pint: ^1.2
- orchestra/testbench: ^7.5
- pestphp/pest: ^1.21
- pestphp/pest-plugin-laravel: ^1.2
- phpunit/phpunit: ^9.5
- thled/pest-plugin-shorthands: ^1.1
This package is auto-updated.
Last update: 2025-03-14 15:18:57 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
Special thanks to Eduardo San Martin Morote (posva) for encoding utlities