1. Go to this page and download the library: Download novius/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/ */
novius / laravel-dto example snippets
use Novius\LaravelDto\Dto;
/**
* @property string $name
* @property int $age
* @property ?string $email
*
* @method string getName()
* @method self setName(string $name)
* @method int getAge()
* @method self setAge(int $age)
* @method ?string getEmail()
* @method self setEmail(?string $email)
*/
class UserDto extends Dto
{
protected string $name;
protected int $age;
protected ?string $email;
}
// Instantiation from an array
$dto = new UserDto([
'name' => 'John Doe',
'age' => 30,
'email' => '[email protected]',
]);
echo $dto->name; // John Doe
/**
* @property string $first_name
*
* @method string getFirstName()
* @method self setFirstName(string $firstName)
*/
class UserDto extends Dto {
protected string $first_name;
}
$dto = new UserDto(['first_name' => 'John']);
echo $dto->firstName; // John
echo $dto->getFirstName(); // John
$dto->setFirstName('Jane');
use Novius\LaravelDto\Dto;
use Novius\LaravelDto\Attributes\Map;
class UserDto extends Dto
{
#[Map('dt-debut')]
protected string $date_begin;
protected string $date_end;
protected function map(): array
{
return [
'date_end' => 'dt-fin',
];
}
}
use Novius\LaravelDto\Attributes\Rules;
class UserDto extends Dto
{
#[Rules('
use Novius\LaravelDto\Attributes\DefaultValue;
class UserDto extends Dto
{
#[DefaultValue(18)]
protected int $age;
}
use Novius\LaravelDto\Attributes\Cast;
class UserDto extends Dto
{
#[Cast('bool')]
protected $is_admin;
#[Cast('datetime:Y-m-d H:i')]
protected Carbon $created_at;
}
use Novius\LaravelDto\Dto;
use Novius\LaravelDto\Attributes\ExcludeFromDTO;
class UserDto extends Dto
{
protected string $name;
#[ExcludeFromDTO]
protected string $internal_token;
}
// This will throw an InvalidArgumentException because internal_token is excluded
$dto = new UserDto(['name' => 'John', 'internal_token' => 'secret']);
// This is also forbidden
$dto = new UserDto(['name' => 'John']);
$dto->internal_token = 'secret'; // Throws InvalidArgumentException