1. Go to this page and download the library: Download sj/dtomatic 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/ */
sj / dtomatic example snippets
return [
'strict_types' => true, //If enabled, Dtomatic will throw an exception when a type mismatch occurs.
'date_format' => 'Y-m-d H:i:s', // The default date format used when converting DateTime objects to strings
//You can register custom type converters here. When mapping a value,
//Dtomatic will check if a converter exists for its type and use it.
'custom_converters' => [
// Example:
// 'string' => \App\Converters\JsonToArrayConverter::class,
],
];
use ShihabJamil\Dtomatic\Attributes\ArrayOf;
class UserDTO
{
#[ArrayOf(PostDTO::class)]
public array $posts;
}
use ShihabJamil\Dtomatic\Attributes\Ignore;
class PostDTO
{
#[Ignore]
public string $internalNotes;
}
use ShihabJamil\Dtomatic\Attributes\Converter;
class PostDTO
{
#[Converter(MyCustomConverter::class)]
public string $specialField;
}
namespace App\DTO;
class UserDTO
{
public int $id;
public string $name;
public string $email;
}
use App\Models\User;
use Dtomatic\Facades\ModelMapper;
use App\DTO\UserDTO;
$user = User::find(1);
$dto = ModelMapper::map($user, UserDTO::class);
return response()->json($dto);
class PostDTO {
public int $id;
public string $title;
public UserDTO $author;
}
$post = Post::with('author')->find(1);
$dto = ModelMapper::map($post, PostDTO::class);
namespace App\Dto;
use ShihabJamil\Dtomatic\Attributes\ArrayOf;
class UserDTO
{
public int $id;
public string $name;
#[ArrayOf(PostDTO::class)]
public array $posts;
}
class PostDTO
{
public int $id;
public string $title;
}
$userModel = User::with('posts')->find(1);
$userDto = ModelMapper::map($userModel, UserDTO::class);
// $userDto->posts is now an array of PostDTO objects
namespace App\Converters;
class UppercaseConverter
{
public function convert(string $value): string
{
return strtoupper($value);
}
}
use Dtomatic\Attributes\Converter;
class UserDTO
{
public int $id;
#[Converter(\App\Converters\UppercaseConverter::class)]
public string $name;
public string $email;
}