PHP code example of bkief29 / laravel-dto

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

    

bkief29 / laravel-dto example snippets




namespace Domain\DTO\Requests;

use bkief29\DTO\DataTransferObject;

/**
 * Class PricesRequest.
 */
class PricesRequest extends DataTransferObject
{

    /**
     * @var string
     */
    public $serviceCode;
    /**
     * @var string
     */
    public $effectiveDate;
    /**
     * @var int
     */
    public $quantity;

    protected $casts = [
        'serviceCode' => 'string',
        'quantity' => 'int',
    ];

    protected $dates = [
        'effectiveDate'
    ];

    public function getEffectiveDateAttribute($date)
    {
        return $date->format($this->getDateFormat());
    }

    // OR

    public function getEffectiveDateAttribute()
    {
        return $this->getOriginal('effectiveDate')->format($this->getDateFormat());
    }
}


class User extends DataTransferObject
{
    ...
        
    public function getNameAttribute($value)
    {
        return ucwords($value);
    }

    // OR

    public function getNameAttribute()
    {
        return ucwords($this->getOriginal('name'));
    }
}


echo $array['name'];
// john smith

$user = new User($array);

echo $user->name; // John Smith
echo $user['name']; // John Smith
echo $user->getAttribute('name'); // John Smith
echo $user->getOriginal('name'); // john smith

class PostData extends DataTransferObject
{
    /** @var string */
    public $title;
    
    /** @var string|null */
    public $body;
    
    /** @var App\DataTransferObjects\Author */
    public $author;
    
    /** @var App\DataTransferObjects\Tag[] */
    public $tags;
}

$postData = new $postData($array);

$postData->author; // Instance of App\DataTransferObjects\Author
$postData->tags; // Array of App\DataTransferObjects\Tag

$postData->all();

$postData
    ->only('title', 'body')
    ->toArray();
    
$postData
    ->except('author')
    ->toArray();

$postData->toCollection();