Links:
Dependencies:
Install php composer from https://getcomposer.org/
Install the neuron MVC component:
composer require neuron-php/dto
Example configuration:
test.yaml
dto:
username:
type: string
length:
min: 3
max: 20
required: true
password:
required: true
type: string
length:
min: 8
max: 10
age:
type: integer
range:
min: 18
max: 40
birthdate:
type: string
format: date
pattern: '/^\d{4}-\d{2}-\d{2}$/' # YYYY-MM-DD format
inventory:
type: array
items:
type: object
properties:
name:
required: true
type: string
amount:
required: true
type: integer
attributes:
type: array
items:
type: string
address:
required: true
type: object
properties:
street:
required: true
type: string
length:
min: 3
max: 10
city:
required: true
type: string
length:
min: 3
max: 20
state:
required: true
type: string
length:
min: 2
max: 2
zip:
required: true
type: string
length:
min: 3
max: 20
Create a DTO.
DTOs support hierarchical/nested parameters.
$DtoFactory = new DtoFactory( 'examples/test.yaml' );
$Dto = $DtoFactory->create();
$Dto->username = 'Fred';
$Dto->address->street = '13 Mockingbird lane.'
$Dto->validate()
print_r( $Dto->getErrors() );
This will display all validation errors for all parameters.
You can also access validation errors for an individual parameter.
print_r( $Dto->getParameter( 'username' )->getErrors() );
To output the contents of the DTO as JSON, use the getAsJson() method.
echo $Dto->getAsJson();
Mappers allow the dynamic mapping of different data structures.
test-json-map.yaml
map:
test.username: user.name
test.password: user.password
test.age: user.age
test.address.street: user.address.street
test.address.city: user.address.city
test.address.state: user.address.state
test.address.zip: user.address.zip
test.inventory: user.inventory
test.inventory.name: user.inventory.name
test.inventory.amount: user.inventory.count
test.inventory.attributes: user.inventory.attributes
Create a mapper, ingest and map external data.
$MapperFactory = new \Neuron\Dto\Mapper\Factory( 'examples/test-json-map.yaml' );
$Mapper = $MapperFactory->create();
$Payload = [
'user' => [
'name' => 'test',
'password' => 'testtest',
'age' => 40,
'birthday' => '1978-01-01',
'address' => [
'street' => '13 Mocking',
'city' => 'Mockingbird Heights',
'state' => 'CA',
'zip' => '90210'
],
'inventory' => [
[
'name' => 'shoes',
'count' => 1,
'attributes' => [
[
'name' => 'leather',
],
[
'name' => 'boot',
],
[
'name' =>'smelly'
]
]
],
[
'name' => 'jackets',
'count' => 2
],
[
'name' => 'pants',
'count' => 3
]
]
]
];
$Mapper->map( $Dto, $Payload );
echo $Dto->username; // outputs 'test'
echo $Dto->inventory[ 1 ]->amount; // outputs 3
echo $Dto->inventory[ 0 ]->attributes[ 1 ]; // outputs 'boot'
What is mapping?
Mapping Arrays multidimensional static items to arrays