PHP code example of zelak / mapper

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

    

zelak / mapper example snippets


class UserDto {
    public int $id;
    public string $username;
    public string $password;
}

$mapper = new Mapper(); // Creating
$mapper->createMap(UserDto::class); // Registering

// Using
$user = new stdClass();
$user->id = "1";
$user->username = "username";
$user->password = "password":

$userDto = $mapper->map($user, UserDto::class);

class ProductDto {
    public string $name;
    public BuyerDto $buyer;
}

class BuyerDto {
    public string $name;
}

$mapper = new Mapper(); // Creating
$mapper->createMap(ProductDto::class); // Registering
$mapper->createMap(BuyerDto::class);

// Using
$buyer = new stdClass();
$buyer->name = "buyerName";
$product = new stdClass();
$product->name = "propName";
$product->buyer = $buyer;

$productDto = $mapper->map($product, ProductDto::class);

class ProductArrDto {
    public string $name;
    public array $buyer;
}

class BuyerDto {
    public string $name;
}

$mapper = new Mapper(); // Creating
$mapper->createMap(ProductArrDto::class) // Registering
    ->specify("buyer", BuyerDto::class); // <-- specifying here
$mapper->createMap(BuyerDto::class);

$mapper = new Mapper();
$mapper->createMap(UserDto::class)
    ->from(function ($from, $to) {
        $to->username = $from->username . " $from->id"
    };);

$mapper = new Mapper();
$mapper->createMap(UserDto::class)
    ->ignore("password")

class UserRenameDto {
    public string $id;
    public string $name;
    public string $password;
}

$mapper = new Mapper(); // Creating
$mapper->createMap(UserRenameDto::class) // Registering
    ->renameProp("username", "name"); // Rename the property

// Using
$user = new stdClass();
$user->id = "1";
$user->username = "username";
$user->password = "password":

$userDto = $mapper->map($user, UserRenameDto::class);

$mapper = new Mapper(); // Creating
$mapper->createMap(ProductDto::class) // Registering
    ->toArrayProp("buyer", "name"); // Map to array
$mapper->createMap(BuyerDto::class);

// Using
$buyer = new stdClass();
$buyer->name = "buyerName";
$product = new stdClass();
$product->name = "propName";
$product->buyer = $buyer;

$productDto = $mapper->map($user, ProductDto::class);