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 static function toUserDTO(object $input): UserDTO
    {
        return new UserDTO([
            'username' => $formatingService->userName($input->display_name),
            'email' => $formatingService->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' => $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::clas, 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 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,
];

$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)

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