Skip to main content

n2n-bind Property based usage

BindSources

A property based bind task can be created by Bind::attrs(), Bind::obj() or Bind::propBindSource(). It expects a key-value element collection type as input such as array, AttributeReader or object. These elements will be called properties in this documentation.

In property based bind tasks you must define which properties should be read from the input and be passed to the output. This functionality can be used to filter the wanted properties.

AttrsBindSource

AttrsBindSource expects an array or AttributeReader as input type.

$bindTask = Bind::attrs()
->props(['prop1', 'prop2'])
->toArray();

$inputArr = ['prop1' => 'val1', 'prop2' => 'val2', 'prop3' => 'val3'];
$result = $bindTask->exec(input: $inputArr);

var_dump($result->get());

Output:

array(2) {
["prop1"]=>
string(4) "val1"
["prop2"]=>
string(4) "val2"
}

If you need to execute the bind task only once for one input you can also pass the input directly to Bind::attrs():

$inputArr = ['prop1' => 'val1', 'prop2' => 'val2', 'prop3' => 'val3'];
$result = Bind::attrs($inputArr)
->props(['prop1', 'prop2'])
->toArray()
->exec();

ObjBindSource

ObjBindSource expects an object as input type.

class InputObj {
function __construct(public string $prop1, public string $prop2, public string $prop3) {}
}

$bindTask = Bind::obj()
->props(['prop1', 'prop2'])
->toArray();

$inputObj = new InputObj('val1', 'val2', 'val3');
$result = $bindTask->exec(input: $inputObj);

var_dump($result->get());

Output:

array(2) {
["prop1"]=>
string(4) "val1"
["prop2"]=>
string(4) "val2"
}

If you need to execute the bind task only once for one input you can also pass the input directly to Bind::obj():

$inputObj = new InputObj('val1', 'val2', 'val3');
$result = Bind::obj($inputObj)
->props(['prop1', 'prop2'])
->toArray()
->exec();

Mappers

For each property Mappers can be defined to modify the value.

$inputArr = ['prop1' => 'val1', 'prop2' => 'val2', 'prop3' => 'val3'];
$result = Bind::attrs()
->props(['prop1', 'prop2'], Mappers::valueClosure(fn (string $v) => $v . '-changed'))
->toArray()
->exec(input: $inputArr);

var_dump($result->get());

Output:

array(2) {
["prop1"]=>
string(12) "val1-changed"
["prop2"]=>
string(12) "val2-changed"
}