PHP code example of yorcreative / laravel-argonaut-dto

1. Go to this page and download the library: Download yorcreative/laravel-argonaut-dto library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yorcreative / laravel-argonaut-dto example snippets


class UserDTO extends ArgonautDTO
{
    public string $username;
    public string $email;

    protected array $casts = [
        'username' => 'string',
        'email' => 'string',
    ];

    public function rules(): array
    {
        return [
            'username' => ['

// static usage example
class UserDTOAssembler extends ArgonautAssembler
{
    public static function toUserDTO(object $input): UserDTO
    {
        return new UserDTO([
            'username' => $input->display_name,
            'email' => $input->email,
        ]);
    }
}

// instance usage example
class UserDTOAssembler extends ArgonautAssembler
{
    public function __construct(protected UserFormattingService $formattingService)
    {
        //
    }

    public function toUserDTO(object $input): UserDTO
    {
        return new UserDTO([
            'username' => $this->formattingService->userName($input->display_name),
            'email' => $this->formattingService->email($input->email),
        ]);
    }
}

// static usage example
$dto = UserDTOAssembler::assemble([
    'display_name' => 'jdoe',
    'email' => '[email protected]',
], UserDTO::class);

// instance usage example
$dto = $userDTOAssemblerInstance->assembleInstance([
    'display_name' => 'jdoe',
    'email' => '[email protected]',
], UserDTO::class);

// static usage
UserDTOAssembler::fromArray($userArray, UserDTO::class);
UserDTOAssembler::fromCollection($userCollection, UserDTO::class);

// instance usage
UserDTOAssembler::fromArray($userArray, UserDTO::class, $userDTOAssemblerInstance);
UserDTOAssembler::fromCollection($userCollection, UserDTO::class, $userDTOAssemblerInstance);

// or using the assembler instance's static methods
$userDTOAssemblerInstance::fromArray($userArray, UserDTO::class, $userDTOAssemblerInstance);
$userDTOAssemblerInstance::fromCollection($userCollection, UserDTO::class, $userDTOAssemblerInstance);

class ProductDTO extends ArgonautDTO
{
    public string $title;
    public array $features;
    public Collection $reviews;
    public ?UserDTO $user = null;

    protected array $casts = [
        'features' => [ProductFeatureDTO::class],
        'reviews' => Collection::class . ':' . ProductReviewDTO::class,
        'user' => UserDTO::class,
    ];

    public function rules(): array
    {
        return [
            'title' => ['

class ProductDTOAssembler extends ArgonautAssembler
{
    public static function toProductDTO(object $input): ProductDTO
    {
        return new ProductDTO([
            'title' => $input->product_name,
            'user' => $input->user,
            'features' => $input->features ?? [],
            'reviews' => $input->reviews ?? [],
        ]);
    }

    public static function toProductFeatureDTO(object $input): ProductFeatureDTO
    {
        return new ProductFeatureDTO([
            'name' => $input->name ?? 'Unnamed Feature',
            'description' => $input->description ?? null,
        ]);
    }

    public static function toProductReviewDTO(object $input): ProductReviewDTO
    {
        return new ProductReviewDTO([
            'rating' => (int) ($input->rating ?? 0),
            'comment' => $input->comment ?? '',
        ]);
    }
}



namespace App\Assemblers;

use App\DTOs\UserDTO;
use App\Services\UserFormattingService;
use YorCreative\LaravelArgonautDTO\ArgonautAssembler;

class UserAssembler extends ArgonautAssembler
{
    public function __construct(protected UserFormattingService $formattingService) 
    {
        //
    }
    
    /**
     * Transform input data into a UserDTO with dependency injection.
     *
     * @param object $input Input data (e.g., from a model or array cast to object).
     * @param UserFormattingService $formatter Injected service for formatting user data.
     * @return UserDTO
     */
    public function toUserDTO(object $input): UserDTO
    {
        return new UserDTO([
            'full_name' => $this->formattingService->formatName($input->first_name, $input->last_name),
            'email' => $input->email,
            'created_at' => $input->created_at,
        ]);
    }
}

// ServiceProvider


namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class YourServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(FormattingServiceInterface::class, function ($app) {
            return new FormattingService();
        });
        $this->app->bind(YourArgonautAssembler::class, function ($app) {
            return new YourArgonautAssembler($app->get(FormattingServiceInterface::class));
        });
    }

    public function provides()
    {
        return [
            YourArgonautAssembler::class,
            FormattingServiceInterface::class,
        ];
    }
}



use App\Assemblers\UserAssembler;
use App\DTOs\UserDTO;

// Example input (e.g., a model or object)
$input = (object) [
    'first_name' => 'John',
    'last_name' => 'Doe',
    'email' => '[email protected]',
    'created_at' => now(),
];

// Creating an assembler instance
$formattingService = new UserFormattingService();
$assembler = new UserAssembler($formattingService);
// or using the container instance
$assembler = resolve(YourArgonautAssembler::class);

// Pass the $assembler instance 
$userDTO = UserAssembler::assemble($input, UserDTO::class, $assembler);
// Or use the instance method
$userDTO = $assembler->assembleInstance($input, UserDTO::class);

// Transform a collection passing the $assembler instance
$array = [$input, $input];
$collection = collect($array);
$userDTOs = UserAssembler::fromCollection($collection, UserDTO::class, $assembler);
$userDTOs = $assembler::fromArray($array, UserDTO::class, $assembler);

class ProductDTO extends ArgonautDTO
{
    public string $title;
    public array $features;
    public Collection $reviews;
    public ?UserDTO $user = null;

    protected array $casts = [
        'features' => [ProductFeatureDTO::class],
        'reviews' => Collection::class . ':' . ProductReviewDTO::class,
        'user' => UserDTO::class,
    ];

    protected array $nestedAssemblers = [
        'user' => UserDTOAssembler::class
    ];

    public function rules(): array
    {
        return [
            'title' => ['

$rawProduct = [
    'title' => 'Standing Desk',
    'user' => ['display_name' => 'jdoe', 'email' => '[email protected]'],
    'features' => [['name' => 'Height Adjustable']],
    'reviews' => [['rating' => 5, 'comment' => 'Great!']],
];

$productDTO = ProductDTOAssembler::assemble($rawProduct, ProductDTO::class);

// $productDTO->user is now a fully assembled UserDTO instance
$this->assertInstanceOf(UserDTO::class, $productDTO->user);
$this->assertSame('jdoe', $productDTO->user->username);

use YorCreative\LaravelArgonautDTO\ArgonautImmutableDTO;
use Illuminate\Support\Carbon;

class UserDTO extends ArgonautImmutableDTO
{
    public readonly string $username;
    public readonly string $email;
    public readonly ?string $firstName;
    public readonly ?string $lastName;
    public readonly ?Carbon $registeredAt;

    protected array $casts = [
        'registeredAt' => Carbon::class,
    ];

    public function rules(): array
    {
        return [
            'username' => ['

// Create an immutable DTO - works exactly like ArgonautDTO
$user = new UserDTO([
    'username' => 'jdoe',
    'email' => '[email protected]',
    'firstName' => 'John',
    'lastName' => 'Doe',
    'registeredAt' => '2024-01-15 10:30:00',
]);

// Access properties normally
echo $user->username;        // 'jdoe'
echo $user->registeredAt;    // Carbon instance

// Serialization works the same
$array = $user->toArray();
$json = $user->toJson();

// Validation works the same
$user->validate();
$user->isValid();

// Attempting to modify throws an Error
$user->username = 'other';   // ❌ Error: Cannot modify readonly property

class UserDTOAssembler extends ArgonautAssembler
{
    public static function toUserDTO(object $input): UserDTO
    {
        return new UserDTO([
            'username' => $input->display_name,
            'email' => $input->email,
            'firstName' => $input->first_name ?? null,
            'lastName' => $input->last_name ?? null,
        ]);
    }
}

// Works exactly the same as mutable DTOs
$user = UserDTOAssembler::assemble($input, UserDTO::class);
$users = UserDTOAssembler::fromArray($userArray, UserDTO::class);
$users = UserDTOAssembler::fromCollection($userCollection, UserDTO::class);

class OrderDTO extends ArgonautImmutableDTO
{
    public readonly string $orderId;
    public readonly UserDTO $customer;           // Single nested DTO
    public readonly array $items;                // Array of DTOs
    public readonly Collection $payments;        // Collection of DTOs

    protected array $casts = [
        'customer' => UserDTO::class,
        'items' => [OrderItemDTO::class],
        'payments' => Collection::class . ':' . PaymentDTO::class,
    ];
}

class UserDTO extends ArgonautDTO
{
    public ?string $firstName = null;
    public ?string $lastName = null;
    public string $username;
    public string $email;
    public ?string $fullName = null;

    protected array $prioritizedAttributes = ['firstName', 'lastName'];

    protected array $casts = [
        'firstName' => 'string',
        'lastName' => 'string',
        'username' => 'string',
        'email' => 'string',
        'fullName' => 'string',
    ];

    public function setFirstName($value)
    {
        $this->firstName = $value;
        $this->fullName = $this->firstName . ' ' . $this->lastName;
    }

    public function setLastName($value)
    {
        $this->lastName = $value;
        $this->fullName = $this->firstName . ' ' . $this->lastName;
    }

    public function rules(): array
    {
        return [
            'firstName' => ['nullable', 'string', 'max:32'],
            'lastName' => ['nullable', 'string', 'max:32'],
            'username' => ['

protected array $casts = [
    'registeredAt' => \Illuminate\Support\Carbon::class,
    'profile' => ProfileDTO::class,
    'roles' => [RoleDTO::class],
    'permissions' => Collection::class . ':' . PermissionDTO::class,
    'status' => StatusEnum::class,
    'tags' => [TagEnum::class],
    'priorities' => Collection::class . ':' . PriorityEnum::class,
];

use App\Enums\StatusEnum; // enum StatusEnum: string { case Active = 'active'; ... }

class TaskDTO extends ArgonautDTO
{
    public ?StatusEnum $status = null;

    protected array $casts = [
        'status' => StatusEnum::class,
    ];
}

$task = new TaskDTO(['status' => 'active']);
$task->status;              // StatusEnum::Active
$task->toArray()['status']; // 'active'

$userDTO->validate();         // Throws ValidationException
$userDTO->validate(false);    // Returns array of errors (non-throwing)
$userDTO->isValid();          // Returns true/false

$userDTO->toArray(); // Recursively converts nested DTOs
$userDTO->toJson();  // JSON output (throws on encoding errors)

$user = new UserDTO([
    'username' => 'jdoe',
    'email' => '[email protected]',
    'firstName' => 'John',
    'lastName' => 'Doe',
]);

$user->only('username', 'email');
// ['username' => 'jdoe', 'email' => '[email protected]']

$user->except('email');
// ['username' => 'jdoe', 'firstName' => 'John', 'lastName' => 'Doe', ...]

$user = new UserDTO(['email' => '[email protected]', 'firstName' => 'John']);

$user->merge(['email' => '[email protected]']);

$user->email;     // '[email protected]'
$user->firstName;  // 'John' (unchanged)

$user->merge(['firstName' => 'Jane'])->merge(['lastName' => 'Doe']);

UserDTO::collection([
    ['username' => 'john', 'email' => '[email protected]'],
]);