#dto #data-transfer-object #php
Based on https://github.com/spatie/data-transfer-object/tree/v2
$object = [
'parameters' => [
[
'name' => 'foo',
'type' => 'text',
'value' => 'bar'
],
[
'name' => 'baz',
'type' => 'select',
'values' => ['foo', 'bar']
]
]
];
The function array_map
will iterate over every parameters
, and for each one it will call Parameters::createFromArray($param)
, which will return an instance of Parameters
based on the type
it finds in the $param
array.
namespace Formio\Dto;
use Spatie\DataTransferObject\FlexibleDataTransferObject;
class Content extends FlexibleDataTransferObject
{
public Parameters $parameters;
public function __construct(array $parameters)
{
parent::__construct($parameters);
$this->parameters = array_map(function($param) {
return \Formio\Dto\Parameters::createFromArray($param);
}, $this->parameters);
}
}
// file Parameters.php
namespace Formio\Dto;
use Spatie\DataTransferObject\FlexibleDataTransferObject;
abstract class Parameters extends FlexibleDataTransferObject
{
public string $name;
public string $type;
public static function createFromArray(array $parameters)
{
switch($parameters['type']) {
case 'select':
return new ParametersSelect($parameters);
default:
return new ParametersText($parameters);
}
}
}
class ParametersSelect extends Parameters
{
public array $values;
}
class ParametersText extends Parameters
{
public string $value;
}
$dto = \Formio\Dto\Content($object)