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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased

- Packages that own tables support a dedicated database connection, `{package}.database.connection`: models, migrations, raw queries, transactions and validation rules all use it (configuration, models, migrations, actions-events).

## 0.4.0

- Requires PHP 8.5.
Expand Down
10 changes: 5 additions & 5 deletions index.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ architecture/public-api:
kind: architectural
enforced_by: []
architecture/configuration:
description: "One self-documenting config/{package}.php with a banner per section (what it controls, values, security and auth middleware for routes); env() only in config; caller options win, cast plus hard default on every read; safe security defaults; opt-in flags false and boolean-coerced; fail loud on a missing entry; table names configurable via {package}.tables."
tags: [architecture, config, tables, defaults]
description: "One self-documenting config/{package}.php with a banner per section (what it controls, values, security, auth middleware for routes); env() only in config; caller options win, cast and default every read; safe security defaults; opt-in flags false and boolean-coerced; fail loud on a missing entry; {package}.tables names; optional own DB via {package}.database.connection."
tags: [architecture, config, tables, defaults, database, connection]
kind: architectural
enforced_by: [pest-arch]
actions/actions-events:
description: "Actions: callers use execute(), action implements protected handle() with a concrete return type and {Action}Data input; starting event, private perform() in DB::transaction(), finished event after commit; read actions have no transaction/events; no model constructor DI; final Dispatchable/SerializesModels event pair."
description: "Actions: callers use execute(), action implements protected handle() with a concrete return type and {Action}Data input; starting event, private perform() in a transaction on the package connection, finished event after commit; read actions have no transaction/events; no model constructor DI; final Dispatchable/SerializesModels event pair."
tags: [actions, events, transactions]
kind: architectural
enforced_by: [pest-arch]
Expand All @@ -58,7 +58,7 @@ data/value-objects:
kind: architectural
enforced_by: []
models/models:
description: "Package Eloquent models: {Entity}Model in Domains/{Domain}/Models, table via getTable() from a configurable {package}.tables map (never literal names), a policy per model from {package}.policies, @property docblocks, typed relation generics, casts, package newFactory(), morph alias on move."
description: "Package Eloquent models: {Entity}Model in Domains/{Domain}/Models, table via getTable() from a configurable {package}.tables map (never literal names), getConnectionName() from {package}.database.connection, a policy per model from {package}.policies, @property docblocks, typed relation generics, casts, package newFactory(), morph alias on move."
tags: [models, eloquent, tables, policies, configuration]
kind: architectural
enforced_by: [pest-arch]
Expand All @@ -68,7 +68,7 @@ models/lifecycle-events:
kind: architectural
enforced_by: [pest-arch]
models/migrations:
description: "Package migrations: fixed date + incrementing sequence filenames, one anonymous-class file per feature's tables, table names and FK targets from the same configurable tables keys as the models, down() in reverse order, publishable via publishesMigrations() and a {package}-migrations tag."
description: "Package migrations: fixed date + incrementing sequence filenames, one anonymous-class file per feature's tables, table names and FK targets from the same configurable tables keys as the models, getConnection() from the package connection, down() in reverse order, publishable via publishesMigrations() and a {package}-migrations tag."
tags: [migrations, database, schema, tables, publishing]
kind: architectural
enforced_by: [pest-arch]
Expand Down
4 changes: 2 additions & 2 deletions standards/actions/actions-events.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ final class Create{Entity}Action extends Action

private function perform(Create{Entity}Data $data, ?Model $owner): {Entity}Model
{
return DB::transaction(fn (): {Entity}Model => {Entity}Model::query()->create([...]));
return Tables::db()->transaction(fn (): {Entity}Model => {Entity}Model::query()->create([...]));
}
}
```
Expand All @@ -38,7 +38,7 @@ final class Create{Entity}Action extends Action
## Transactions & events

- `handle()` dispatches the **starting** event with the input, calls a private `perform()`, dispatches the **finished** event with the result, and returns it.
- Every write in a mutating `perform()` — even a single one — goes inside `DB::transaction()`.
- Every write in a mutating `perform()` — even a single one — goes inside a transaction on the package's connection (`Tables::db()->transaction()`, not `DB::transaction()`, which opens it on the default connection); see [[configuration]].
- Finished events dispatch after commit (`ShouldDispatchAfterCommit`), so they wait for the outermost transaction and never fire on rollback. An action that throws fires its starting event and no finished event.
- When a caller needs post-commit column values, `return $model->refresh();` **outside** the transaction.

Expand Down
8 changes: 7 additions & 1 deletion standards/architecture/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ Each package has one config file, `config/{package}.php`, that documents itself,
- Table names are configurable through a `{package}.tables` map of key to default name. Models resolve `getTable()` from it and migrations use the same keys, never a literal table name; see [[models]] and [[migrations]].
- A published config that lists only some tables keeps the defaults for the rest.

## Database connection

- Every package that owns tables lets a host keep them on a dedicated connection through `{package}.database.connection` (env default `{PACKAGE}_DB_CONNECTION`), documented in its own config section. Null, the default, means the app's default connection.
- Everything that touches the package's tables uses that connection: models (`getConnectionName()`), migrations (`getConnection()`), raw queries, schema checks, transactions and `exists`/`unique` rules (`{connection}.{table}`). Never the `DB` facade or an injected default `ConnectionInterface`, which go to the default connection.
- Joins, subqueries and `whereHas` across the package's tables and host tables (users, teams) only work while both sit on one database; the config section says so.

## Reference implementation (Refactor Circus)

Each package's `Support\Tables` extends Keystone's `Database\Tables`, setting `CONFIG = '{package}.tables'` and `DEFAULTS`; `Tables::name('{entities}')` serves models and migrations. `tests/ArchTest.php` rejects literal table names with Keystone's `Arch::literalTableNames()`. `Support\ServiceProvider::loadApiRoutesFrom()` reads `routes.enabled`, `routes.prefix` and `routes.middleware` from the package config.
Each package's `Support\Tables` extends Keystone's `Database\Tables`, setting `CONFIG = '{package}.tables'` and `DEFAULTS`; `Tables::name('{entities}')` serves models and migrations. `Tables::connection()` reads `{package}.database.connection`, `Tables::db()` is that connection for queries and transactions, and `Tables::qualified('{entities}')` names a table for validation rules. `tests/ArchTest.php` rejects literal table names with Keystone's `Arch::literalTableNames()` and default-connection access with `Arch::defaultConnectionUses()`. `Support\ServiceProvider::loadApiRoutesFrom()` reads `routes.enabled`, `routes.prefix` and `routes.middleware` from the package config.
13 changes: 13 additions & 0 deletions standards/models/migrations.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@ Schema::create(Tables::name('{entity}_items'), function (Blueprint $table): void
});
```

## Connection

- Each migration returns the package's configured connection from `getConnection()`, so its tables are created on the package's own database when one is configured (`{package}.database.connection`; null is the app default). Laravel runs `up()`/`down()` with that connection as the default, so `Schema::` inside them follows it.

```php
public function getConnection(): ?string
{
return Tables::connection();
}
```

- Foreign keys only reach tables on the same connection. A key to a host table (users) is a plain indexed column when the package may live on its own database.

## Loading and publishing

- The package service provider loads migrations from `database/migrations` and registers them with `publishesMigrations()` under the package tag and a `{package}-migrations` tag, so a host can publish and edit them. See [[service-providers]].
Expand Down
6 changes: 6 additions & 0 deletions standards/models/models.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ A package model is `{Entity}Model` in `Domains/{Domain}/Models`, resolves its ta
## Tables

- Override `getTable()` to return the table's configured name by key, from the package's tables class (backed by the `{package}.tables` config). Never set `$table` to a literal or write a prefixed table name anywhere else — package tables live in a host app, which may need to rename them.
- Override `getConnectionName()` to return the model's own connection when set, else the package's configured connection (`{package}.database.connection`), so a host can move the package to its own database; see [[configuration]].
- Default names carry the package prefix (`{package}_{entities}`), so they don't collide with host tables.
- Migrations, validation rules (`Rule::exists(...)`) and joins ask the same tables class with the same keys; see [[migrations]] and [[configuration]].

Expand Down Expand Up @@ -41,6 +42,11 @@ class {Entity}Model extends Model
{
return Tables::name('{entities}');
}

public function getConnectionName(): ?string
{
return $this->connection ?? Tables::connection();
}
}
```

Expand Down
Loading