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
14 changes: 12 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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<Model>`. 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
Expand Down
35 changes: 34 additions & 1 deletion docs/guide/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>`, `Mapping<T>` and `ReadQuery<T>` use PHPDoc generics, where `T` is an object. `T` is covariant, so `Repository<Product>` is accepted where `Repository<object>` 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<T>`, `Mapping<T>` and `ReadQuery<T>` use PHPDoc generics, where `T` is an object. `T` is covariant, so `Repository<Product>` is accepted where `Repository<object>` 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).

Expand Down Expand Up @@ -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<Product> */
final readonly class ProductRepository extends Repository
{
public function __construct(Connection $connection)
{
parent::__construct($connection, self::mapping());
}

/** @return Mapping<Product> */
public static function mapping(): Mapping
{
return new Mapping(table: 'products', columns: [/* … */], hydrate: static fn(array $row): Product => /* … */);
}

/** @return list<Product> */
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
Expand Down
4 changes: 2 additions & 2 deletions docs/guide/details.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ withLocale(string $locale, ?string $fallback = null): ReadQuery;
with(array $relations): ReadQuery; // list<string|Load>
```

Последние две — короткие формы `read()->withLocale(...)` и `read()->with(...)`. Обычное чтение выглядит как `$products->read()->find($id)`. Бизнес-методы приложения могут оборачивать этот API; наследоваться от `BaseRepository` больше не требуется.
Последние две — короткие формы `read()->withLocale(...)` и `read()->with(...)`. Обычное чтение выглядит как `$products->read()->find($id)`. Бизнес-методы приложения живут в сервисе, который владеет репозиторием, или в типизированном наследнике `Repository`: `readonly`-класс задаёт маппинг в своём конструкторе, контейнер внедряет его по типу, а статический анализ берёт модель из `@extends Repository<Model>`. Публичные методы `Repository` final — наследник добавляет свои методы, но не меняет унаследованные чтения и записи.

Контракт `ReadQuery<T>`:

Expand Down Expand Up @@ -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` |
Expand Down
4 changes: 2 additions & 2 deletions docs/guide/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 |
Expand Down
39 changes: 22 additions & 17 deletions src/Repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -44,13 +49,13 @@ public function __construct(Connection $connection, private Mapping $mapping, ?i
}

/** @return ReadQuery<T> */
public function read(): ReadQuery
final public function read(): ReadQuery
{
return new ReadQuery($this->db, $this->mapping, Visibility::Active, null, LoadPlan::from([]));
}

/** @return ReadQuery<T> */
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);
}
Expand All @@ -59,29 +64,29 @@ public function withLocale(string $locale, ?string $fallback = null): ReadQuery
* @param list<string|Load> $relations
* @return ReadQuery<T>
*/
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<string, mixed> $data */
public function insert(array $data): int
final public function insert(array $data): int
{
return $this->executeInsert($this->validateInsert($data));
}

/** @param array<string, mixed> $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);
Expand Down Expand Up @@ -119,7 +124,7 @@ public function insertGetId(array $data): int|string
*
* @param list<array<string, mixed>> $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.');
Expand All @@ -144,7 +149,7 @@ public function insertMany(array $rows, int $batchSize = 500): int
}

/** @param array<string, mixed> $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);
}
Expand All @@ -153,7 +158,7 @@ public function update(int|string $id, array $patch): int
* @param array<string, mixed>|Filter $criteria
* @param array<string, mixed> $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) {
Expand All @@ -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<string, mixed>|Filter $criteria */
public function deleteBy(array|Filter $criteria): int
final public function deleteBy(array|Filter $criteria): int
{
$column = $this->mapping->softDeleteColumn;
if ($column === null) {
Expand All @@ -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.');
Expand All @@ -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<string, mixed>|Filter $criteria */
public function purgeBy(array|Filter $criteria): int
final public function purgeBy(array|Filter $criteria): int
{
return $this->executeDelete($criteria, Visibility::All);
}
Expand All @@ -219,7 +224,7 @@ public function purgeBy(array|Filter $criteria): int
*
* @param int|string|list<int|string> $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]));
Expand Down
15 changes: 15 additions & 0 deletions tests/Core/Fixtures/Note.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Solo\Repository\Tests\Core\Fixtures;

final class Note
{
public function __construct(
public readonly int $id,
public readonly string $title,
public readonly int $done,
) {
}
}
40 changes: 40 additions & 0 deletions tests/Core/Fixtures/NoteRepository.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace Solo\Repository\Tests\Core\Fixtures;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Types\Types;
use Solo\Repository\Mapping;
use Solo\Repository\Repository;

/**
* A typed repository: the mapping is fixed in the constructor, so a container
* can inject it by class, and the table's own queries live beside it.
*
* @extends Repository<Note>
*/
final readonly class NoteRepository extends Repository
{
public function __construct(Connection $connection)
{
parent::__construct($connection, self::mapping());
}

/** @return Mapping<Note> */
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<Note> */
public function open(): array
{
return $this->read()->findBy(['done' => 0], ['id' => 'ASC']);
}
}
51 changes: 51 additions & 0 deletions tests/Core/RepositorySubclassTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

namespace Solo\Repository\Tests\Core;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use ReflectionMethod;
use Solo\Repository\Repository;
use Solo\Repository\Tests\Core\Fixtures\Note;
use Solo\Repository\Tests\Core\Fixtures\NoteRepository;

final class RepositorySubclassTest extends TestCase
{
private Connection $db;

protected function setUp(): void
{
$this->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());
}
}
}
22 changes: 22 additions & 0 deletions tests/Types/PublicApiTypes.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,28 @@ function mappingsWithoutAHydratorReadRows(Connection $connection): void
acceptsAnyRepository($repository);
}

/** @extends Repository<Product> */
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<Solo\Repository\Tests\Types\Product>', $repository->read()->findBy());

acceptsAnyRepository($repository);
}

function relationsInferTheirOwnerAndTarget(): void
{
$categories = categoryMapping();
Expand Down
Loading