-
Notifications
You must be signed in to change notification settings - Fork 2
SchemaGenerator
Viames Marino edited this page Apr 22, 2026
·
2 revisions
Pair\Api\OpenApi\SchemaGenerator generates OpenAPI/JSON Schema definitions from ActiveRecord models and DB metadata.
Use SchemaGenerator to keep API schemas aligned with current model binds/table definitions and to avoid manual schema drift.
Builds full object schema from table description and model binds.
Builds create-request schema:
- removes auto fields (
createdAt,updatedAt, ...) - removes auto-increment key fields
- optionally uses validation rules to define required fields and allowed properties
Builds update schema from create schema, with all fields optional.
Clears generated schema metadata cached by this SchemaGenerator instance.
Invalidate one class:
$g->clearCache(\App\Orm\Order::class);Invalidate every cached schema in the generator instance:
$g->clearCache();Maps MySQL column types to OpenAPI types/formats (integer, number/float, string/date-time, boolean, object, binary).
Also handles:
-
tinyint(1)-> boolean -
enum-> string withenum -
set-> array of enum strings - nullable columns -> union with
null - defaults -> typed
defaultvalues - auto-increment/virtual columns ->
readOnly: true
use Pair\Api\OpenApi\SchemaGenerator;
$g = new SchemaGenerator();
$itemSchema = $g->generate(App\Models\Faq::class);
$createSchema = $g->generateCreateSchema(App\Models\Faq::class, [
'question' => 'required|string|min:3',
'answer' => 'required|string|min:3',
]);
$updateSchema = $g->generateUpdateSchema(App\Models\Faq::class, [
'question' => 'string|min:3',
'answer' => 'string|min:3',
]);- Uses
Database::describeTable()and modelgetBinds(). - Uses
TABLE_KEYto identify key fields. - Caches generated full/create/update schemas per generator instance.
- Use
clearCache()in long-running schema export commands that modify model, read-model, or table metadata before generating again.
$g = new \Pair\Api\OpenApi\SchemaGenerator();
$components = [
'User' => $g->generate(\App\Orm\User::class),
'Order' => $g->generate(\App\Orm\Order::class),
];$create = $g->generateCreateSchema(\App\Orm\Order::class, [
'customerId' => 'required|int',
'total' => 'required|numeric|min:0.01',
]);
$update = $g->generateUpdateSchema(\App\Orm\Order::class, [
'total' => 'numeric|min:0.01',
'note' => 'string|max:500',
]);- Assuming generated schema enforces all business logic constraints.
- Using stale DB metadata in environments with unapplied migrations.
- Forgetting nullable/default semantics when adding custom schema overrides.
- Reusing the same generator after changing metadata without clearing its cache.
See also: SpecGenerator, Database, ActiveRecord.