Skip to main content

n2n-bind in Controllers

n2n-bind is typically used in controllers to map the body of a http request to an object (e.g. a struct object which is then passed to a facade method).

Unmarshal the request body​

SimpleBind::unmarshalAttrs() creates a bind task which unmarshals the input with the #[Unmarshal] mapper of the passed class (see UnmarshalMapper). It is a shorthand for:

Bind::attrs()->root(Mappers::unmarshal(NewGroupStruct::class))->toValue()

The struct object only has to provide an unmarshal mapper, e.g. by using ObjectUnmarshalTrait:

class NewGroupStruct {
use ObjectUnmarshalTrait;

public Label $name;
public ?Text $description = null;
}

In the controller the bind task is executed with $this->exec() and the body of the request as input. Since the bind task is not executed directly, it can be combined with MagicTasks::pipe() with a facade method which accepts the struct object and returns a TaskResult:

class GroupApiController extends ControllerAdapter {

#[Inject]
private GroupFacade $groupFacade;

function postDoNewGroup(ParamBody $body): void {
$httpData = $body->parseJsonToHttpData();

$execResult = $this->exec(SimpleBind::unmarshalAttrs(NewGroupStruct::class), $httpData);
if ($execResult->sendErrJson()) {
return;
}

$newGroupStruct = $execResult->get();

// ..
}
}
  • $body->parseJsonToHttpData() parses the json body. An invalid json body leads to a StatusException (400).
  • If the body does not have the expected structure (e.g. a property has the wrong type), $this->exec() throws a StatusException (400).
  • If the body is valid in structure but the values are not (e.g. name is too long), or the facade method returns an invalid TaskResult, $execResult->sendErrJson() sends the error map as json to the client and returns true.
  • Otherwise $execResult->get() returns the result of the last task of the pipe, here the created NewGroupStruct.

See Executing Tasks for more details about $this->exec().