Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions CHANGELOG-7.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,16 @@ classes: use the classes directly.

All of them are in the `ByJG\MicroOrm\MapperFunctions` namespace.

### A mapper function given as a class name is created once

`FieldMapping` created a mapper function given as a class name (`withSelectFunction(StandardMapper::class)`,
the default of every field) for **each value**: on reading, for every field of every row. It is now created
once per `FieldMapping`, at its first use, and reused for every row and query, as a function given as an
instance already was. Each `with*Function()` replaces it.

Only a custom mapper class that keeps state between calls of `processedValue()` is affected: make it
stateless (it gets the value, the instance and the executor in each call).

### Observer scope: global → per executor
- Observers now fire for writes flowing through the `DatabaseExecutor` instance(s) of the
repository where they were registered. Two repositories over different executors no longer
Expand Down Expand Up @@ -183,6 +193,24 @@ All of them are in the `ByJG\MicroOrm\MapperFunctions` namespace.
- The protected property `Query::$limitEnd` that stores it is renamed to `Query::$limitQuantity`. Subclasses of
`Query` reading or writing `$this->limitEnd` must use `$this->limitQuantity`

## Performance

Reading entities (`get()`, `getByQuery()`, `getByFilter()`, `ActiveRecord`) is about 5x faster than at the
start of 7.0 development: 20,000 entities with `getByQuery()`, MySQL ~152 ms -> ~29 ms, SQLite ~147 ms ->
~32 ms (PHP 8.5, Xdebug off). From this library:

- `MapFromDbToInstanceHandler` fills each entity itself (byjg/anydataset-db `EntityHydratorInterface`):
the property, the field mapping (`selectFunction`) and how the entity takes each column
(byjg/serializer `ObjectCopy::writerFor()`) are resolved once per query, and each row is one loop, with
the same result as before (pinned by `MapFromDbToInstanceHandlerTest`).
- The mapper functions given as a class name are created once (see Breaking Changes).
- `getByQuery()` with several mappers (a join) builds the entities of each mapper with the mapping resolved once
per query (the new `Mapper::entityHydrator()`), instead of for each row; `Mapper::getEntity()` uses the same
hydrator. Same result as before (pinned by `MapFromDbToInstanceHandlerTest::testGetEntityBuildsAsBefore`).

The rest comes from byjg/anydataset-db and byjg/serializer 7.0 (entity defaults read once per query,
`ObjectCopy` direct array copy and write resolution cached per class).

## Bug Fixes

- `Repository::getByFilter()` paging (and `ActiveRecord::all()`, which uses it) returned the wrong rows past the
Expand All @@ -205,6 +233,7 @@ All of them are in the `ByJG\MicroOrm\MapperFunctions` namespace.
| `Repository` subclass overriding `insert()`/`update()` | Update to the new `OrmSqlStatement` signatures |
| `match` over `ObserverEvent` | Add the `SoftDelete` arm |
| `->limit(start: $s, end: $n)` (named argument) | `->limit(start: $s, limit: $n)` |
| Custom mapper function class that keeps state per call | Make it stateless: it is created once per `FieldMapping` |

## Requirements

Expand Down
11 changes: 9 additions & 2 deletions docs/controlling-the-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,19 @@ The `withUpdateFunction`, `withInsertFunction`, and `withSelectFunction` methods
Unlike earlier versions, **you cannot pass a closure or callable directly**. You must create a class implementing
`MapperFunctionInterface`.

:::note One instance, reused
A class name is created once per `FieldMapping` and reused for every row and query: keep a mapper function
stateless. See [Keep a mapper function stateless](mapper-functions.md#keep-a-mapper-function-stateless).
:::

## Arguments passed to the processedValue method

The `processedValue` method in your custom mapper class will receive three arguments:

- `$value`: The value of the field in the entity class
- `$instance`: The instance of the entity class
- `$value`: The value of the field
- `$instance`: for an update or insert function, the instance of the entity class being saved (`null` when a
primary key is converted for a lookup, as in `get()`); for a select function, the row read: an array of the
columns, merged over the properties of a new entity
- `$executor`: The instance of the DatabaseExecutor. You can use it to query the database or convert the value to the
database format.

Expand Down
25 changes: 24 additions & 1 deletion docs/mapper-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,9 @@ class MyCustomMapper implements MapperFunctionInterface
The `processedValue` method receives:

- `$value`: The current value of the field
- `$instance`: The entity instance being processed
- `$instance`: for an update or insert function, the entity instance being saved (`null` when a primary key is
converted for a lookup, as in `get()`); for a select function, the row read: an array of the columns, merged
over the properties of a new entity
- `$executor`: The database executor that allows query the database or provides database-specific functions

You can then use your custom mapper function just like the built-in ones:
Expand All @@ -151,6 +153,27 @@ You can then use your custom mapper function just like the built-in ones:
protected $myField;
```

### Keep a mapper function stateless

A mapper function given as a class name (`MyCustomMapper::class`) is created **once** per field mapping, at its
first use, and that instance is reused for every row, every save and every query, as an instance you pass
(`new MyCustomMapper()`) is. Do not keep state between calls of `processedValue()` (a counter, the previous
value, a cache of the entity): everything a call needs comes in its arguments.

```php
// Wrong: the second row sees the first row's value
class RunningTotalMapper implements MapperFunctionInterface
{
private int $total = 0;

public function processedValue(mixed $value, mixed $instance, ?DatabaseExecutor $executor = null): mixed
{
$this->total += (int)$value;
return $this->total;
}
}
```

## How Mapper Functions Work

- **Select**: When data is retrieved from the database, the `selectFunction` is applied to transform the value before
Expand Down
24 changes: 24 additions & 0 deletions docs/using-mapper-object.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,30 @@ $mapper->addFieldMapping(
);
```

### Building entities from rows

The `Repository` builds the entities of its queries for you. To build them from values you already have (a raw
query, an import, a test), use the mapper: the field names are mapped to the properties, and the select functions
are applied, as when the repository reads them.

```php
<?php
// One entity
$user = $mapper->getEntity(['id' => 10, 'name' => 'Joao', 'createdate' => '2020-01-01']);

// Many rows of one query: entityHydrator() resolves the mapping once, then builds each entity
$hydrate = $mapper->entityHydrator();
$users = [];
foreach ($executor->getIterator('SELECT * FROM users') as $row) {
$users[] = $hydrate($row->toArray());
}
```

`getEntity()` resolves the mapping on each call; for many rows, `entityHydrator()` is several times faster. The
properties without a value in the row take the values of a new entity, read once per hydrator (see
[Entity Mapping](https://github.com/byjg/php-anydataset-db/blob/master/docs/entity.md#property-mapping)).
`getByQuery()` with several mappers (a join) uses one hydrator per mapper.

## Summary

| Feature | Attributes | Mapper Objects |
Expand Down
41 changes: 29 additions & 12 deletions src/FieldMapping.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ class FieldMapping
*/
private string $fieldAlias;

/**
* The instance of each function given as a class name, created once (at its first use) instead of for each value
*
* @var array<string, MapperFunctionInterface>
*/
private array $functionInstances = [];

private bool $syncWithDb = true;

private ?string $parentTable = null;
Expand Down Expand Up @@ -83,6 +90,7 @@ public function withUpdateFunction(MapperFunctionInterface|string $updateFunctio
}

$this->updateFunction = $updateFunction;
unset($this->functionInstances['update']);
return $this;
}

Expand All @@ -93,6 +101,7 @@ public function withSelectFunction(MapperFunctionInterface|string $selectFunctio
}

$this->selectFunction = $selectFunction;
unset($this->functionInstances['select']);
return $this;
}

Expand All @@ -103,6 +112,7 @@ public function withInsertFunction(MapperFunctionInterface|string $insertFunctio
}

$this->insertFunction = $insertFunction;
unset($this->functionInstances['insert']);
return $this;
}

Expand Down Expand Up @@ -165,30 +175,37 @@ public function getFieldAlias(): ?string
return $this->fieldAlias;
}

public function getSelectFunctionValue(mixed $value, mixed $instance): mixed
/**
* The function itself, or the instance of its class name, created once and reused for every value
*/
private function functionInstance(string $kind, MapperFunctionInterface|string $function): MapperFunctionInterface
{
$function = $this->selectFunction;
if (is_string($function)) {
$function = new $function();
if (!is_string($function)) {
return $function;
}
if (!isset($this->functionInstances[$kind])) {
/** @var MapperFunctionInterface $instance */
$instance = new $function();
$this->functionInstances[$kind] = $instance;
}
return $this->functionInstances[$kind];
}

public function getSelectFunctionValue(mixed $value, mixed $instance): mixed
{
$function = $this->functionInstance('select', $this->selectFunction);
return $function->processedValue($value, $instance, null);
}

public function getUpdateFunctionValue(mixed $value, mixed $instance, ?DatabaseExecutor $executor = null): mixed
{
$function = $this->updateFunction;
if (is_string($function)) {
$function = new $function();
}
$function = $this->functionInstance('update', $this->updateFunction);
return $function->processedValue($value, $instance, $executor);
}

public function getInsertFunctionValue(mixed $value, mixed $instance, ?DatabaseExecutor $executor = null): mixed
{
$function = $this->insertFunction;
if (is_string($function)) {
$function = new $function();
}
$function = $this->functionInstance('insert', $this->insertFunction);
return $function->processedValue($value, $instance, $executor);
}

Expand Down
36 changes: 22 additions & 14 deletions src/Mapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
use ByJG\MicroOrm\Interface\MapperFunctionInterface;
use ByJG\MicroOrm\Literal\LiteralInterface;
use ByJG\MicroOrm\PropertyHandler\MapFromDbToInstanceHandler;
use ByJG\Serializer\ObjectCopy;
use ByJG\Serializer\Serialize;
use Closure;
use ReflectionAttribute;
use ReflectionClass;
use ReflectionException;
Expand Down Expand Up @@ -229,20 +229,28 @@ public function getEntityClass(): string
*/
public function getEntity(array $fieldValues = []): object
{
$class = $this->entity;
$instance = new $class();

// The command below is to get all properties of the class.
// This will allow processing all properties, even if they are not in the $fieldValues array.
// Particularly useful for processing the selectFunction.
$fieldValues = array_merge(Serialize::from($instance)->withStopAtFirstLevel()->toArray(), $fieldValues);
ObjectCopy::copy($fieldValues, $instance, new MapFromDbToInstanceHandler($this));

if (is_array($instance)) {
$instance = (object)$instance;
}
return ($this->entityHydrator())($fieldValues);
}

return $instance;
/**
* A function that builds an entity of this mapper from the values of a row (field names), with the mapping
* resolved once for all the rows it builds: the properties of a new entity are read once (at the first level,
* so the properties without a value in the row are processed too, e.g. by a selectFunction), and a
* MapFromDbToInstanceHandler fills each entity. For the rows of one query, such as a join of several mappers.
*
* @return Closure(array): object
*/
public function entityHydrator(): Closure
{
$class = $this->entity;
$handler = new MapFromDbToInstanceHandler($this);
$defaults = Serialize::from(new $class())->withStopAtFirstLevel()->toArray();

return static function (array $fieldValues) use ($class, $handler, $defaults): object {
$instance = new $class();
$handler->hydrate($fieldValues, $instance, $defaults);
return $instance;
};
}

public function getQuery(): Query
Expand Down
87 changes: 84 additions & 3 deletions src/PropertyHandler/MapFromDbToInstanceHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,96 @@

namespace ByJG\MicroOrm\PropertyHandler;

use BackedEnum;
use ByJG\AnyDataset\Db\Interfaces\EntityHydratorInterface;
use ByJG\MicroOrm\FieldMapping;
use ByJG\MicroOrm\Mapper;
use ByJG\Serializer\ObjectCopy;
use ByJG\Serializer\PropertyHandler\PropertyHandlerInterface;
use Override;
use stdClass;

class MapFromDbToInstanceHandler implements PropertyHandlerInterface
/**
* Maps the columns of a row to the properties of the entity of a Mapper (property names, selectFunction).
*
* As a property handler, ObjectCopy calls it for each value. As an entity hydrator, it fills each entity itself
* with the same result: how each column is written is resolved once per query, and each row is one loop.
*/
class MapFromDbToInstanceHandler implements PropertyHandlerInterface, EntityHydratorInterface
{

protected ?FieldMapping $fieldMap = null;

/**
* The property name and the field mapping of each field name, resolved once (the handler lives for a query)
*
* @var array<string, array{0: string, 1: FieldMapping|null}>
*/
private array $fields = [];

/**
* How each column is written, resolved once (the handler lives for a query): the property name, the field
* mapping, and ObjectCopy::writerFor() of the entity class
*
* @var array<string, array{0: string, 1: FieldMapping|null, 2: array{0: string, 1: bool, 2: class-string<BackedEnum>|null}|false}>
*/
private array $plan = [];

public function __construct(private Mapper $mapper)
{
}

/**
* The same values as ObjectCopy::copy(array_merge($defaults, $row), $entity, $this): for each key in that
* order, the property name (mapName()), the selectFunction (transformValue()), then the setter or the public
* property of the entity, as ObjectCopy writes it (a backed enum member takes the enum).
*/
#[Override]
public function hydrate(array $row, object $entity, array $defaults): void
{
$source = array_merge($defaults, $row);
$className = get_class($entity);
$isStdClass = $entity instanceof stdClass;

foreach ($source as $key => $value) {
$key = (string)$key;
if (!isset($this->plan[$key])) {
$propertyName = $this->mapName($key);
$this->plan[$key] = [
$propertyName,
$this->fieldMap,
$isStdClass ? false : ObjectCopy::writerFor($className, $propertyName),
];
}
[$propertyName, $fieldMap, $writer] = $this->plan[$key];

if ($value instanceof BackedEnum) {
$value = $value->value;
}
if ($fieldMap !== null) {
$value = $fieldMap->getSelectFunctionValue($value, $source) ?? $value;
}

if ($writer === false) {
// stdClass takes any name; another class, a property the instance has (dynamic or magic)
if ($isStdClass || isset($entity->{$propertyName})) {
$entity->{$propertyName} = $value;
}
continue;
}

[$member, $isSetter, $enum] = $writer;
if ($enum !== null && (is_int($value) || is_string($value))) {
$value = $enum::from($value);
}
if ($isSetter) {
$entity->{$member}($value);
continue;
}
$entity->{$member} = $value;
}
}

#[Override]
/**
* Note:
Expand All @@ -26,8 +103,12 @@ public function __construct(private Mapper $mapper)
*/
public function mapName(string $property): string
{
$propertyName = $this->mapper->getPropertyName($property);
$this->fieldMap = $this->mapper->getFieldMap($propertyName);
if (!isset($this->fields[$property])) {
$propertyName = $this->mapper->getPropertyName($property);
$fieldMap = $this->mapper->getFieldMap($propertyName);
$this->fields[$property] = [$propertyName, $fieldMap instanceof FieldMapping ? $fieldMap : null];
}
[$propertyName, $this->fieldMap] = $this->fields[$property];
return $propertyName;
}

Expand Down
Loading
Loading