Skip to content

Extending

Property accessors

A property of a mapped class is read by a reader and written by a writer. They are chosen by a strategy once per property, on the first conversion of the class.

The metadata give each direction of a property its access point: the backing value of the property (StorageAccessPoint), its PHP 8.4 hook (HookAccessPoint) or a method (MethodAccessPoint). By default the backing value is written directly or by reflection for private and readonly properties, bypassing its hooks, a virtual property is accessed through its hooks, a method is called.

An access strategy takes the point of its direction and returns the reader or the writer, or null for a point it does not take. A strategy may take one direction only. Strategies of the user are tried first.

A strategy that goes through the getter and the setter of a property:

use TypeLang\Mapper\Mapping\Metadata\AccessPoint\StorageAccessPoint;
use TypeLang\Mapper\Mapping\Metadata\PropertyMetadata;
use TypeLang\Mapper\PropertyAccessor\PropertyReader\MethodPropertyReader;
use TypeLang\Mapper\PropertyAccessor\PropertyReaderInterface;
use TypeLang\Mapper\PropertyAccessor\PropertyWriter\MethodPropertyWriter;
use TypeLang\Mapper\PropertyAccessor\PropertyWriterInterface;
use TypeLang\Mapper\PropertyAccessor\Strategy\AccessStrategyInterface;
final class AccessorMethodsStrategy implements AccessStrategyInterface
{
public function tryCreateReader(
\ReflectionClass $class,
PropertyMetadata $metadata,
): ?PropertyReaderInterface {
$point = $metadata->read?->point;
// only a property with its own value
if (!$point instanceof StorageAccessPoint) {
return null;
}
$method = 'get' . \ucfirst($point->property);
if (!$class->hasMethod($method)) {
return null;
}
return new MethodPropertyReader($method);
}
public function tryCreateWriter(/* ... */): ?PropertyWriterInterface
{
// the same with $metadata->write, the "set" prefix
// and MethodPropertyWriter
}
}
final class Customer
{
public string $name;
public function getName(): string { /* ... */ }
public function setName(string $name): void
{
$this->name = \strtolower($name);
}
}
$mapper = new Mapper(accessors: [new AccessorMethodsStrategy()]);
$mapper->denormalize(['name' => 'JOHN'], Customer::class);
// Customer { name: 'john' }

The strategy chooses how to access the point, not the field of the data: which properties are mapped and under which names is decided by the metadata. The value reaches the writer already converted to the type of the direction.