PHP code example of negreanucalin / sparkle-dto

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

    

negreanucalin / sparkle-dto example snippets


use SparkleDto\DataTransferObject;

class UserDto extends DataTransferObject
{
    protected $casts = [
        'id'         => 'int',
        'active'     => 'bool',
        'created_at' => 'datetime',        // becomes a Carbon instance
        'address'    => AddressDto::class, // nested DTO
        'roles'      => RoleDto::class,    // list of DTOs (numeric keys)
    ];

    protected $alias = ['first_name' => 'name']; // rename incoming keys

    protected $hidden = ['password']; // readable, but left out of JSON/toString

    // Computed property: available as $dto->full_name
    public function getFullNameAttribute(): string
    {
        return $this->name . ' ' . $this->surname;
    }
}

$user = new UserDto($request->all());

$user->id;            // int
$user->created_at;    // Carbon
$user->address->city; // AddressDto
$user->full_name;     // computed
json_encode($user);   // hidden fields excluded