PHP code example of olexin-pro / data-transfer-object
1. Go to this page and download the library: Download olexin-pro/data-transfer-object 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/ */
olexin-pro / data-transfer-object example snippets
namespace App\DTO;
use Ol3x1n\DataTransferObject\AbstractDTO;
use Ol3x1n\DataTransferObject\Field;
use Ol3x1n\DataTransferObject\Enums\TypeEnum;
class UserDTO extends AbstractDTO
{
#[Field('id', TypeEnum::INT,
$data = [
'id' => '5', // Will be cast to int(5)
'name' => 'Alex',
'profile' => [ // Will be hydrated into ProfileDTO
'age' => '30',
'country' => 'USA'
]
];
$dto = new UserDTO($data);
echo $dto->id; // 5 (int)
echo $dto->profile->country; // "USA"
class ProfileDTO extends AbstractDTO
{
#[Field('age', TypeEnum::INT)]
public ?int $age;
}
class UserDTO extends AbstractDTO
{
#[Field('profile', TypeEnum::DTO)]
public ProfileDTO $profile;
}
use App\DTO\UserDTO;
class UserController extends Controller
{
public function store(UserDTO $dto)
{
// $dto is already validated and hydrated from the request
$user = $this->service->create($dto);
return new UserResource($user);
}
}
public function update(Request $request)
{
$dto = UserDTO::fromRequest($request);
}
use Ol3x1n\DataTransferObject\Laravel\DTOCast;
use App\DTO\ProfileDTO;
class User extends Model
{
protected $casts = [
'profile' => ProfileDTO::class,
];
}
$user->profile->age = 31;
$user->save(); // Saved as JSON column
class UserResource extends JsonResource
{
public function toArray($request)
{
// Works whether $this->resource is a Model or a DTO
return [
'id' => $this->id,
'name' => $this->name,
];
}
}
// Returning a DTO directly
return new UserResource($userDTO);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.