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);