PHP code example of alvarez / concrete-dto

1. Go to this page and download the library: Download alvarez/concrete-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/ */

    

alvarez / concrete-dto example snippets




use Alvarez\ConcreteDto\AbstractDTO;

final class UserDTO extends AbstractDTO
{
    public function __construct(
        public readonly string $name,
        public readonly string $email,
    ) {}
}

// From array
$user = UserDTO::fromArray([
    'name' => 'Daniel Alvarez',
    'email' => '[email protected]',
]);

// From JSON
$user = UserDTO::fromJSON('{"name":"Daniel Alvarez","email":"[email protected]"}');

// From custom object
use Alvarez\ConcreteDto\Contracts\DTOFrom;
use Alvarez\ConcreteDto\Contracts\IsDTO;

final class UserRequestToDTO implements DTOFrom
{
    public static function handle(mixed $dataToConvert): IsDTO
    {
        return new UserDTO(
            name: $dataToConvert->fullName,
            email: $dataToConvert->contact,
        );
    }
}

$request = new UserRequest('Daniel Alvarez', '[email protected]');
$user = UserDTO::from(UserRequestToDTO::class, $request);

// To array
$data = $user->toArray();
// ['name' => 'Daniel Alvarez', 'email' => '[email protected]']

// To JSON
$json = $user->toJson();
// {"name":"Daniel Alvarez","email":"[email protected]"}

// To custom object
use Alvarez\ConcreteDto\Contracts\DTOTo;

final class UserDTOToModel implements DTOTo
{
    public static function handle(IsDTO $dto): mixed
    {
        return new UserModel(name: $dto->name, email: $dto->email);
    }
}

$model = $user->to(UserDTOToModel::class);

// Filter fields
$publicData = $user->except(['email']);
// ['name' => 'Daniel Alvarez']

// Clone with updates
$updated = $user->cloneWith(['email' => '[email protected]']);
// Original $user remains unchanged

final class UserDTO extends AbstractDTO
{
    public function __construct(
        public readonly string $name,
        public readonly string $email,
    ) {
        self::validate($this->toArray()); // Enable validation on direct instantiation
    }

    public static function validate(array $data): void
    {
        if (!filter_var($data['email'] ?? '', FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException('Invalid email format');
        }
        
        if (strlen($data['name'] ?? '') < 2) {
            throw new InvalidArgumentException('Name too short');
        }
    }
}

// Validation runs automatically
$user = UserDTO::fromArray(['name' => 'Daniel', 'email' => 'invalid']);
// Throws InvalidArgumentException

$user = new UserDTO('A', 'invalid@email');
// Also throws InvalidArgumentException because validate is called in constructor

Route::get('/user/{id}', function (Request $request) {
    $user = User::find($request->id);
    return response()->json($user->toArray());
});

dispatch(new SendEmailJob($user->toJson()));

class SendEmailJob
{
    public function handle()
    {
        $user = UserDTO::fromJSON($this->userData);
        Mail::to($user->email)->send(new WelcomeEmail($user));
    }
}

// Map DTO to Eloquent model for persistence
$userModel = $userDTO->to(UserDTOToModel::class);
$userModel->save();

// Remove email before caching user data
$cacheData = $user->except(['email']);
Cache::put("user.{$user->name}", $cacheData);