Skip to content

Extending

Instantiators

An instantiator creates the objects of a class, or finds existing ones. It is chosen by a strategy once per class, on the first conversion of the class.

By default an object is created without its constructor. An instantiation strategy takes a class and returns the instantiator of its objects, or null for a class it does not take: the next strategy is tried, the built-in one is the last.

The instantiator gets the data the object is filled from, so it may find an existing object instead of creating one, such as an entity to update:

use TypeLang\Mapper\Instantiator\InstantiatorInterface;
use TypeLang\Mapper\Instantiator\Strategy\InstantiationStrategyInterface;
use TypeLang\Mapper\Mapper;
// Finds the account of the data or creates a new one
final class AccountInstantiator implements InstantiatorInterface
{
public function __construct(private AccountRepository $accounts) {}
public function instantiate(array $data = []): object
{
return $this->accounts->find($data['id'] ?? null) ?? new Account();
}
}
// Gives the instantiator to the Account class only
final class AccountStrategy implements InstantiationStrategyInterface
{
public function __construct(private AccountRepository $accounts) {}
public function tryCreateInstantiator(
\ReflectionClass $class,
/* ... */
): ?InstantiatorInterface {
if ($class->name !== Account::class) {
return null;
}
return new AccountInstantiator($this->accounts);
}
}
$mapper = new Mapper(instantiators: [new AccountStrategy($accounts)]);
$mapper->denormalize(['id' => 1, 'email' => 'new@example.com'], Account::class);
// the account 1 of the repository, with the new email

The instantiator is called by the conversion only. A check of the data, such as the choice of a branch of Account|int, creates no object.