jnariai / simple-dto
A simple data transfer object for Laravel
Fund package maintenance!
SimpleDTO
Requires
- php: ^8.2
- illuminate/contracts: ^12.0||^11.0
- spatie/laravel-package-tools: ^1.16
Requires (Dev)
- larastan/larastan: ^2.9||^3.0
- laravel/pint: ^1.14
- nunomaduro/collision: ^8.1.1||^7.10.0
- orchestra/testbench: ^10.0.0||^9.0.0||^8.22.0
- pestphp/pest: ^3.0
- pestphp/pest-plugin-arch: ^3.0
- pestphp/pest-plugin-faker: ^3.0
- phpstan/extension-installer: ^1.3||^2.0
- phpstan/phpstan-deprecation-rules: ^1.1||^2.0
- phpstan/phpstan-phpunit: ^1.3||^2.0
- rector/rector: ^2.0
README
Immutable Data Transfer Object (DTO) for PHP inspired by Laravel Data and Bags
Introduction
This is a package to create minimal immutable Data Transfer Object for PHP with some handy features like the method from to create the dto from array, it implements Arrayable
and Jsonable
interfaces, and also has two attributes to use #[NonNullOutput]
and #[Hidden]
to help in the output transformation.
Installation
You can install the package via composer:
composer require jnariai/simple-dto
Usage
use SimpleDTO\DTO; final readonly class MyDTO extends DTO { public function __construct( public bool $property_bool, public ?string $property_string, public string $sensitive_data, ) {} }
You can create the DTO using the static function from::
and pass an array of data
$myDTO = MyDTO::from([ 'property_bool' => true, 'sensitive_data' => 'sensitive data', ]); // You don't need to pass properties that can be null, it will automatically be set to null /* MyDTO { +property_bool: true +property_string: null +sensitive_data: "sensitive data" } */
You can also get a toArray an toJson method
$myDTO->toArray(); // ['property_bool' => true, 'property_string' => null, 'sensitive_data' => 'sensitive data'] $myDTO->toJson(); // {"property_bool":true,"property_string":null,"sensitive_data":"sensitive data"}
You also get two available attributes to use. #[NonNullOutput]
and #[Hidden]
.
#[NonNullOutput]
is a class Attribute and when using toArray or toJson it will only return properties that are not null.
use SimpleDTO\DTO; #[NonNullOutput] final readonly class MyDTO extends DTO { public function __construct( public bool $property_bool, public ?string $property_string, public string $sensitive_data, ) {} } $myDTO->toArray(); // ['property_bool' => true, 'sensitive_data' => 'sensitive data'] $myDTO->toJson(); // {"property_bool":true,"sensitive_data":"sensitive data"}
#[Hidden]
is a property Attribute and when using toArray or toJson it will not return the property.
use SimpleDTO\DTO; final readonly class MyDTO extends DTO { public function __construct( public bool $property_bool, public ?string $property_string, #[Hidden] public string $sensitive_data, ) {} } $myDTO->toArray(); // ['property_bool' => true, 'property_string' => null] $myDTO->toJson(); // {"property_bool":true,"property_string":null}
License
The MIT License (MIT). Please see License File for more information.