PHP code example of mcustiel / php-simple-conversion

1. Go to this page and download the library: Download mcustiel/php-simple-conversion 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/ */

    

mcustiel / php-simple-conversion example snippets


class DatabaseRegisterRepresentationForPerson 
{
    private $id;
    private $jsonString;

    public function __construct($id, $jsonString)
    {
        $this->id = $id;
        $this->jsonString = $jsonString;
    }
    // ... Getters and setters
}

class DomainRepresentationForPerson
{
    private $id;
    private $firstName;
    private $lastName;
    private $age;
    
    // ... Getters and setters
}

use Mcustiel\PhpSimpleConversion\Converter;

// class DBPersonToLogicPersonConverter (MUST implement Converter interface)
class DBPersonToLogicPersonConverter implements Converter
{
    public function convert($a)
    {
        if (! ($a instanceof DatabaseRegisterRepresentationForPerson)) {
            throw new \InvalidArgumentException("Should convert only from DatabaseRegisterRepresentationForPerson");
        }
        $return = new DomainRepresentationForPerson();

        $return->setId($a->getId());
        $object = json_decode($a->getJsonString());
        $return->setFirstName($object->firstName);
        $return->setLastName($object->lastName);
        $return->setAge($object->age);

        return $return;
    }
}

use Mcustiel\PhpSimpleConversion\ConversionService;
use Mcustiel\PhpSimpleConversion\ConverterBuilder;

$conversionService = new ConversionService();
// ...
$converter = ConverterBuilder::get()
    ->from(DatabaseRegisterRepresentationForPerson::class)
    ->to(DomainRepresentationForPerson::class)
    ->withImplementation(DBPersonToLogicPersonConverter::class); // Implementation could be the name of the class or an instance
$conversionService->registerConverter($converter);

    $dbPerson = $personDao->getPerson('alice');
    $logicPerson = $conversionService->convert($dbPerson, DomainRepresentationForPerson::class);

use Mcustiel\PhpSimpleConversion\ConversionService;
use Mcustiel\PhpSimpleConversion\ConverterBuilder;

$conversionService = new ConversionService();
// ...
$converter = ConverterBuilder::get()
    ->from(C::class)
    ->to(A::class)
    ->withImplementation(CtoAConverter::class);
$conversionService->registerConverter($converter);
$b = new B();
$a = $conversionService->convert($b, A::class, ConversionService::ALLOW_PARENTS);
javascript
" ...
        "mcustiel/php-simple-conversion": "*"
    }