From 07c25faf24a4ea7d2c7c313ebc20915ca6fc7ef2 Mon Sep 17 00:00:00 2001 From: vitaliyolos Date: Tue, 27 Oct 2026 10:49:52 +0200 Subject: [PATCH] feat: let applications extend Repository into typed repositories Repository is no longer final. An application can extend it with a readonly class that fixes the mapping in its own constructor, so a container injects each table's repository by type and static analysis reads the model from @extends Repository. Every public method except the constructor is final: a subclass adds methods of its own and cannot change the inherited reads and writes. --- CHANGELOG.md | 14 ++++++- docs/guide/api.md | 35 +++++++++++++++++- docs/guide/details.md | 4 +- docs/guide/migration.md | 4 +- src/Repository.php | 39 +++++++++++--------- tests/Core/Fixtures/Note.php | 15 ++++++++ tests/Core/Fixtures/NoteRepository.php | 40 ++++++++++++++++++++ tests/Core/RepositorySubclassTest.php | 51 ++++++++++++++++++++++++++ tests/Types/PublicApiTypes.php | 22 +++++++++++ 9 files changed, 200 insertions(+), 24 deletions(-) create mode 100644 tests/Core/Fixtures/Note.php create mode 100644 tests/Core/Fixtures/NoteRepository.php create mode 100644 tests/Core/RepositorySubclassTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index ace7866..f3fbe49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,9 @@ Initial release of **Solo Repository** (`solophp/repository`) with the ### Features -- Explicit, typed `Mapping` and composition-based `Repository`; constructing - repositories and queries never opens a database connection. +- Explicit, typed `Mapping` and `Repository`; constructing repositories and + queries never opens a database connection. An application can extend + `Repository` into a typed repository per table; its public methods are final. - Reusable `ReadQuery` with projection reads, `sum`/`min`/`max`/`avg` aggregates over the same criteria as `count`, bounded integer-ID iteration, and `queryBuilder()`, a DBAL `QueryBuilder` over the rows its criteria select. @@ -35,6 +36,15 @@ Initial release of **Solo Repository** (`solophp/repository`) with the `insertMany`, and many-to-many `LinkSet` operations. - SQLite tests, MySQL 8.4/MariaDB 12.3/PostgreSQL 17 integration tests, and a PHP/DBAL CI matrix. +### Changes since 1.0.0-RC3 + +- `Repository` is no longer final. An application can extend it with a + `readonly` class that fixes the mapping in its own constructor, so a + container injects each table's repository by type and static analysis reads + the model from `@extends Repository`. Every public method except the + constructor is final: a subclass adds methods and cannot change the + inherited reads and writes. + ### Changes since 1.0.0-RC2 - `IN` and `NOT IN` criteria and the key lists of relation loads and diff --git a/docs/guide/api.md b/docs/guide/api.md index 36b9f5d..0817513 100644 --- a/docs/guide/api.md +++ b/docs/guide/api.md @@ -2,7 +2,7 @@ This reference describes Solo Repository 1.0: PHP 8.3+, Doctrine DBAL `^4.3`, and the `Solo\Repository` namespace. Relation definitions live in `Solo\Repository\Relations`. See the [design and integration guide](details.md) and `examples/definitions.php` in the source checkout. -`Repository`, `Mapping` and `ReadQuery` use PHPDoc generics, where `T` is an object. `T` is covariant, so `Repository` is accepted where `Repository` is expected. Relation definitions are generic over their owner and target models, so static analysis checks every `assign` callback against the target mapping. The runtime checks that hydration and relation assignment return objects; it does not enforce their concrete class. These classes, the configuration objects and the write helpers are `final readonly`. Readonly configuration does not make the shared DBAL connection, returned models or objects captured by callbacks immutable. +`Repository`, `Mapping` and `ReadQuery` use PHPDoc generics, where `T` is an object. `T` is covariant, so `Repository` is accepted where `Repository` is expected. Relation definitions are generic over their owner and target models, so static analysis checks every `assign` callback against the target mapping. The runtime checks that hydration and relation assignment return objects; it does not enforce their concrete class. `Mapping`, `ReadQuery`, the configuration objects and the write helpers are `final readonly`; `Repository` is `readonly` and may be extended into a [typed repository](#typed-repositories). Readonly configuration does not make the shared DBAL connection, returned models or objects captured by callbacks immutable. The public API consists of the types and methods documented below. The `Internal` namespace and members marked `@internal` are implementation details without a semantic-versioning compatibility promise: the constructors of `ReadQuery`, `LinkSet` and `TranslationStore` (obtain them from a `Repository`), the properties of `Filter`, and `Relations\Relation::resolve()`. The abstract `Relation` base is not an extension point: use the four supplied final definitions. The legacy `BaseRepository`, `RepositoryInterface` and singular `Relation` namespace belong to the separate `solophp/base-repository` package; see the [migration guide](migration.md). @@ -48,6 +48,39 @@ $product = $products->read()->find($id); // Product|null $products->update($id, ['price' => '179.90']); // affected rows; no model reread ``` +## Typed repositories + +An application may extend `Repository` with a `readonly` class that fixes the mapping in its own constructor. Each table then has a class of its own: a container can inject it by type, static analysis knows its model from `@extends`, and queries about that table can live beside it. The public methods of `Repository` are final, so a subclass adds a constructor and methods of its own and cannot change what the inherited ones do; the repository's state stays private to it. + +```php +use Doctrine\DBAL\Connection; + +/** @extends Repository */ +final readonly class ProductRepository extends Repository +{ + public function __construct(Connection $connection) + { + parent::__construct($connection, self::mapping()); + } + + /** @return Mapping */ + public static function mapping(): Mapping + { + return new Mapping(table: 'products', columns: [/* … */], hydrate: static fn(array $row): Product => /* … */); + } + + /** @return list */ + public function cheaperThan(string $price): array + { + return $this->read()->findBy(['price <' => $price], ['price' => 'ASC']); + } +} + +$product = (new ProductRepository($db))->read()->find($id); // Product|null +``` + +A `readonly` class can only be extended by a `readonly` class. A static `mapping()` also gives relations a target factory: `target: ProductRepository::mapping(...)`. + ## Mapping and types ```php diff --git a/docs/guide/details.md b/docs/guide/details.md index c28d12b..33cf2e0 100644 --- a/docs/guide/details.md +++ b/docs/guide/details.md @@ -137,7 +137,7 @@ withLocale(string $locale, ?string $fallback = null): ReadQuery; with(array $relations): ReadQuery; // list ``` -Последние две — короткие формы `read()->withLocale(...)` и `read()->with(...)`. Обычное чтение выглядит как `$products->read()->find($id)`. Бизнес-методы приложения могут оборачивать этот API; наследоваться от `BaseRepository` больше не требуется. +Последние две — короткие формы `read()->withLocale(...)` и `read()->with(...)`. Обычное чтение выглядит как `$products->read()->find($id)`. Бизнес-методы приложения живут в сервисе, который владеет репозиторием, или в типизированном наследнике `Repository`: `readonly`-класс задаёт маппинг в своём конструкторе, контейнер внедряет его по типу, а статический анализ берёт модель из `@extends Repository`. Публичные методы `Repository` final — наследник добавляет свои методы, но не меняет унаследованные чтения и записи. Контракт `ReadQuery`: @@ -366,7 +366,7 @@ SQL builder, экранирование, параметры, типы и тра | V3 | Solo Repository | |---|---| -| Наследование и protected-настройки | `new Repository($db, new Mapping(...))`, композиция по умолчанию | +| Наследование и protected-настройки | `new Repository($db, new Mapping(...))` или типизированный наследник, который задаёт маппинг в своём конструкторе; публичные методы `Repository` final | | Статический метод mapper по имени | Типизированный callable; `Model::fromArray(...)` адаптируется к преобразованным DBAL значениям | | Изменяемые/одноразовые `withLocale`, `with` | Независимый повторно используемый `ReadQuery` | | `find/findBy` на репозитории | `read()->find/findBy`, либо сразу `withLocale/with` | diff --git a/docs/guide/migration.md b/docs/guide/migration.md index b0cc97c..e59f772 100644 --- a/docs/guide/migration.md +++ b/docs/guide/migration.md @@ -66,7 +66,7 @@ final class ProductRepository extends BaseRepository } ``` -Solo Repository `Repository` is final. Construct it from the application's DBAL `Connection` and a `Mapping`; keep domain-specific methods in a service or a wrapper that owns that repository. Inject the same connection separately wherever the application needs SQL or transactions. +Construct a Solo Repository `Repository` from the application's DBAL `Connection` and a `Mapping`, or extend it into a [typed repository](api.md#typed-repositories) whose constructor fixes the mapping. Its public methods are final: a subclass adds methods of its own, it does not override reads or writes. Inject the same connection separately wherever the application needs SQL or transactions. ```php use Doctrine\DBAL\Types\Types; @@ -469,7 +469,7 @@ The following v3 extension points have no equivalent in Solo Repository: | V3 feature | Migration | |---|---| -| `RepositoryInterface` / subclassing `BaseRepository` | Own an instance of final `Repository`; define an application interface if needed | +| `RepositoryInterface` / subclassing `BaseRepository` | Extend `Repository` into a typed repository with a fixed mapping, or own an instance; its public methods are final. Define an application interface if needed | | `getConnection()` and protected `queryBuilder()` | Inject `Connection` into the application component | | Protected `table()` with `applyCriteria()` | `read()->queryBuilder($alias, $criteria)`; add the SELECT, joins and `andWhere()` conditions to the returned DBAL builder | | `beginTransaction()/commit()/rollBack()/withTransaction()/inTransaction()` | Use DBAL `Connection` transaction methods | diff --git a/src/Repository.php b/src/Repository.php index c3b4323..ef5d78e 100644 --- a/src/Repository.php +++ b/src/Repository.php @@ -24,9 +24,14 @@ /** * Explicit writes and independent read queries over one mapped table. * + * An application may extend it with a readonly class that fixes the mapping in + * its own constructor, giving each table a typed service to inject, and adds + * methods of its own. The public methods are final: a subclass adds to the + * repository and cannot change what it does. + * * @template-covariant T of object */ -final readonly class Repository +readonly class Repository { private Database $db; @@ -44,13 +49,13 @@ public function __construct(Connection $connection, private Mapping $mapping, ?i } /** @return ReadQuery */ - public function read(): ReadQuery + final public function read(): ReadQuery { return new ReadQuery($this->db, $this->mapping, Visibility::Active, null, LoadPlan::from([])); } /** @return ReadQuery */ - public function withLocale(string $locale, ?string $fallback = null): ReadQuery + final public function withLocale(string $locale, ?string $fallback = null): ReadQuery { return $this->read()->withLocale($locale, $fallback); } @@ -59,29 +64,29 @@ public function withLocale(string $locale, ?string $fallback = null): ReadQuery * @param list $relations * @return ReadQuery */ - public function with(array $relations): ReadQuery + final public function with(array $relations): ReadQuery { return $this->read()->with($relations); } - public function links(string $relation): LinkSet + final public function links(string $relation): LinkSet { return new LinkSet($this->db, $this->mapping, $relation); } - public function translations(): TranslationStore + final public function translations(): TranslationStore { return new TranslationStore($this->db, $this->mapping); } /** @param array $data */ - public function insert(array $data): int + final public function insert(array $data): int { return $this->executeInsert($this->validateInsert($data)); } /** @param array $data */ - public function insertGetId(array $data): int|string + final public function insertGetId(array $data): int|string { $key = $this->mapping->requirePrimaryKey('insertGetId()'); $data = $this->validateInsert($data); @@ -119,7 +124,7 @@ public function insertGetId(array $data): int|string * * @param list> $rows */ - public function insertMany(array $rows, int $batchSize = 500): int + final public function insertMany(array $rows, int $batchSize = 500): int { if ($batchSize < 1) { throw new InvalidArgumentException('Expected a positive batch size.'); @@ -144,7 +149,7 @@ public function insertMany(array $rows, int $batchSize = 500): int } /** @param array $patch */ - public function update(int|string $id, array $patch): int + final public function update(int|string $id, array $patch): int { return $this->updateBy([$this->mapping->requirePrimaryKey('update()') => $this->mapper->id($id)], $patch); } @@ -153,7 +158,7 @@ public function update(int|string $id, array $patch): int * @param array|Filter $criteria * @param array $patch */ - public function updateBy(array|Filter $criteria, array $patch): int + final public function updateBy(array|Filter $criteria, array $patch): int { $this->validateColumns($patch); foreach ([$this->mapping->primaryKey, $this->mapping->softDeleteColumn] as $reserved) { @@ -165,13 +170,13 @@ public function updateBy(array|Filter $criteria, array $patch): int return $this->executeUpdate($criteria, $patch, Visibility::Active); } - public function delete(int|string $id): int + final public function delete(int|string $id): int { return $this->deleteBy([$this->mapping->requirePrimaryKey('delete()') => $this->mapper->id($id)]); } /** @param array|Filter $criteria */ - public function deleteBy(array|Filter $criteria): int + final public function deleteBy(array|Filter $criteria): int { $column = $this->mapping->softDeleteColumn; if ($column === null) { @@ -188,7 +193,7 @@ public function deleteBy(array|Filter $criteria): int return $this->executeUpdate($criteria, [$column => $value], Visibility::Active); } - public function restore(int|string $id): int + final public function restore(int|string $id): int { if ($this->mapping->softDeleteColumn === null) { throw new LogicException('Restore requires a soft-delete column.'); @@ -201,13 +206,13 @@ public function restore(int|string $id): int ); } - public function purge(int|string $id): int + final public function purge(int|string $id): int { return $this->purgeBy([$this->mapping->requirePrimaryKey('purge()') => $this->mapper->id($id)]); } /** @param array|Filter $criteria */ - public function purgeBy(array|Filter $criteria): int + final public function purgeBy(array|Filter $criteria): int { return $this->executeDelete($criteria, Visibility::All); } @@ -219,7 +224,7 @@ public function purgeBy(array|Filter $criteria): int * * @param int|string|list $ids */ - public function lockForUpdate(int|string|array $ids): void + final public function lockForUpdate(int|string|array $ids): void { $column = $this->mapping->requirePrimaryKey('lockForUpdate()'); $ids = array_values($this->mapper->ids(is_array($ids) ? $ids : [$ids])); diff --git a/tests/Core/Fixtures/Note.php b/tests/Core/Fixtures/Note.php new file mode 100644 index 0000000..3a462aa --- /dev/null +++ b/tests/Core/Fixtures/Note.php @@ -0,0 +1,15 @@ + + */ +final readonly class NoteRepository extends Repository +{ + public function __construct(Connection $connection) + { + parent::__construct($connection, self::mapping()); + } + + /** @return Mapping */ + public static function mapping(): Mapping + { + return new Mapping( + table: 'notes', + columns: ['id' => Types::INTEGER, 'title' => Types::STRING, 'done' => Types::SMALLINT], + hydrate: static fn (array $row): Note => new Note(...$row), + ); + } + + /** @return list */ + public function open(): array + { + return $this->read()->findBy(['done' => 0], ['id' => 'ASC']); + } +} diff --git a/tests/Core/RepositorySubclassTest.php b/tests/Core/RepositorySubclassTest.php new file mode 100644 index 0000000..bf9581e --- /dev/null +++ b/tests/Core/RepositorySubclassTest.php @@ -0,0 +1,51 @@ +db = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true]); + $this->db->executeStatement( + 'CREATE TABLE notes (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, done INTEGER NOT NULL DEFAULT 0)' + ); + } + + public function testASubclassFixesItsMappingAndAddsItsOwnMethods(): void + { + $notes = new NoteRepository($this->db); + $id = $notes->insertGetId(['title' => 'Write tests']); + $notes->insert(['title' => 'Ship', 'done' => 1]); + + $note = $notes->read()->find($id); + self::assertInstanceOf(Note::class, $note); + self::assertSame('Write tests', $note->title); + self::assertSame(['Write tests'], array_map(static fn (Note $note): string => $note->title, $notes->open())); + self::assertSame(1, $notes->update($id, ['done' => 1])); + self::assertSame([], $notes->open()); + } + + public function testASubclassMayRedeclareOnlyTheConstructor(): void + { + $repository = new ReflectionClass(Repository::class); + self::assertFalse($repository->isFinal()); + self::assertTrue($repository->isReadOnly()); + foreach ($repository->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { + self::assertSame($method->getName() !== '__construct', $method->isFinal(), $method->getName()); + } + } +} diff --git a/tests/Types/PublicApiTypes.php b/tests/Types/PublicApiTypes.php index fd6e327..e23e27e 100644 --- a/tests/Types/PublicApiTypes.php +++ b/tests/Types/PublicApiTypes.php @@ -131,6 +131,28 @@ function mappingsWithoutAHydratorReadRows(Connection $connection): void acceptsAnyRepository($repository); } +/** @extends Repository */ +final readonly class ProductRepository extends Repository +{ + public function __construct(Connection $connection) + { + parent::__construct($connection, new Mapping( + table: 'products', + columns: ['id' => Types::INTEGER, 'category_id' => Types::INTEGER], + hydrate: static fn (array $row): Product => new Product(), + )); + } +} + +function typedRepositoriesKeepTheirModel(Connection $connection): void +{ + $repository = new ProductRepository($connection); + assertType('Solo\Repository\Tests\Types\Product|null', $repository->read()->find(1)); + assertType('list', $repository->read()->findBy()); + + acceptsAnyRepository($repository); +} + function relationsInferTheirOwnerAndTarget(): void { $categories = categoryMapping();