Search by

ziraphp / orm

Subu-07

PDO database layer for ZiraPHP: connections with read replicas, query builder, Active Record models, schema builder and migrations.

v0.1.0 2026-12-04 08:09 UTC

This package is auto-updated.

Last update: 2026-12-04 08:17:21 UTC


README

The database layer for ZiraPHP: PDO connections with read replicas, a query builder, Active Record models, a schema builder and migrations.

  • MySQL/MariaDB, PostgreSQL and SQLite.
  • Values are always bound and identifiers are always validated and quoted.
  • Reads go to a replica until you write, then stick to the primary.
  • Models with casts, mass-assignment protection, relations and eager loading.
  • Migrations that run in transactions where the database allows it.
composer require ziraphp/orm

Requires PHP 8.2+, ext-pdo with the driver you use, and ziraphp/framework ^0.1. Add ziraphp/console for the migrate commands and ziraphp/service-provider to configure it from config/database.php.

Setup

In a ZiraPHP application

With ziraphp/service-provider, OrmServiceProvider is discovered automatically and reads config/database.php:

// config/database.php
return [
    'default' => 'mysql',
    'connections' => [
        'mysql' => [
            'driver' => 'mysql',
            'host' => '127.0.0.1',
            'port' => 3306,
            'database' => 'app',
            'username' => 'app',
            'password' => getenv('DB_PASSWORD') ?: '',
            'read' => ['host' => 'replica.internal'], // optional
        ],
        'sqlite' => ['driver' => 'sqlite', 'database' => 'var/app.sqlite'],
    ],
    'migrations' => [
        'table' => 'migrations',
        'paths' => ['database/migrations'], // relative to the application's base path
    ],
];

Without it, register the provider with the configuration:

$app->register(new OrmServiceProvider([
    'connections' => ['main' => ['driver' => 'sqlite', 'database' => 'var/app.sqlite']],
]));

The provider binds ConnectionManager, the default Connection, Migrator and DataStoreInterface (as PdoDataStore), connects models, and adds the migrate commands to ziraphp/console.

On its own

use ZiraPHP\Orm\ConnectionManager;
use ZiraPHP\Orm\Model\Model;

$db = new ConnectionManager([
    'connections' => ['main' => ['driver' => 'sqlite', 'database' => 'var/app.sqlite']],
]);
Model::setConnectionResolver($db);

$connection = $db->connection();

Connection options

Key Drivers Default
driver all required: mysql, pgsql or sqlite
database all required for MySQL and PostgreSQL; :memory: for SQLite
host, port mysql, pgsql 127.0.0.1, 3306 / 5432
username, password mysql, pgsql none
unix_socket mysql none
charset, collation mysql utf8mb4, server default
charset, schema, sslmode pgsql utf8, server default, none
foreign_keys sqlite true
dsn all built from the keys above
options all PDO attributes, merged over ours
read all keys that differ for the read replica

Connections open on first use. PDO always throws, fetches associative arrays and uses native prepared statements.

Queries

$posts = $connection->table('posts')
    ->select('id', 'title')
    ->where('published', true)
    ->where('views', '>', 100)
    ->whereIn('category_id', [1, 2, 3])
    ->orWhere(fn ($q) => $q->whereNull('archived_at')->where('pinned', true))
    ->latest()
    ->limit(20)
    ->get();                       // list of associative arrays
Need Call
Rows get(), first(), find($id), value('col'), pluck('col', 'key')
Conditions where, orWhere, whereIn, whereNotIn, whereNull, whereNotNull, whereBetween, whereColumn, whereExists, whereRaw
Joins join, leftJoin, rightJoin, crossJoin, or a closure with on() / where()
Grouping groupBy, having, havingRaw
Order and paging orderBy, orderByDesc, latest, oldest, limit, offset, forPage, paginate($perPage, $page), chunk
Aggregates count, sum, avg, min, max, exists, doesntExist
Writes insert (one row or many), insertGetId, update, updateOrInsert, increment, decrement, delete, truncate
Locks lockForUpdate, sharedLock
Debugging toSql, getBindings

where('col', $value) means =. Operators come from a fixed list (=, <, >, <=, >=, <>, !=, like, not like, ilike, not ilike), and identifiers may only contain letters, digits and underscores (table.column, column as alias and table.* work). For anything else use an Expression, whose SQL is inserted as written, so never build it from user input:

use ZiraPHP\Orm\Expression;

$connection->table('posts')->where('score', '>', new Expression('likes * ?', [2]))->get();
$connection->table('posts')->selectRaw('count(*) as total')->groupBy('user_id')->get();

Subqueries are closures: whereIn('id', fn ($q) => $q->from('bans')->select('user_id')).

Raw SQL and transactions

$rows = $connection->select('select * from users where id = ?', [1]);
$count = $connection->scalar('select count(*) from users');
$affected = $connection->update('update users set active = ? where id = ?', [false, 1]);

$connection->transaction(function (Connection $db): void {
    $db->table('accounts')->where('id', 1)->decrement('balance', 100);
    $db->table('accounts')->where('id', 2)->increment('balance', 100);
});

Nested transaction() calls use savepoints. A failed statement throws QueryException, which carries the SQL and bindings; a failed connection throws ConnectionException.

Read replicas

With a read key, reads go to the replica and writes to the primary. After the first write on a connection, reads also use the primary so the caller sees its own writes; reads inside a transaction always do. If the replica cannot be reached, reads fall back to the primary.

$connection->select($sql, $bindings, useReplica: false); // force the primary
$connection->stickToPrimary();                          // for the rest of the request
$manager->resetStickiness();                            // at the start of the next one
$connection->status();                                  // replica, sticky, replica_failed...

Long-running workers should call resetStickiness() between jobs or requests.

Query log

$connection->listen(function (QueryExecuted $query): void {
    error_log(sprintf('%.1f ms %s', $query->milliseconds, $query->sql));
});

Models

use ZiraPHP\Orm\Model\Model;
use ZiraPHP\Orm\Model\Relation\BelongsTo;
use ZiraPHP\Orm\Model\Relation\HasMany;

/**
 * @property int $id
 * @property string $title
 * @property bool $published
 * @property list<Comment> $comments
 */
final class Post extends Model
{
    protected array $fillable = ['title', 'body', 'published', 'meta'];
    protected array $casts = ['published' => 'bool', 'meta' => 'array', 'published_at' => 'datetime'];
    protected array $hidden = ['internal_notes'];

    /** @return BelongsTo<User> */
    public function author(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /** @return HasMany<Comment> */
    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class);
    }
}
$post = Post::create(['title' => 'Hello', 'published' => true]);
$post->title = 'Hello, world';
$post->save();

$post = Post::find(1);              // or findOrFail(1)
$posts = Post::where('published', true)->with('author', 'comments')->latest()->get();
$page = Post::query()->orderBy('id')->paginate(15, $currentPage);

$post->comments()->create(['body' => 'Nice']);
$post->author()->associate($user)->save();
$post->delete();
  • Table: the plural snake case of the class name (BlogPost → blog_posts); set protected ?string $table to override.
  • Keys: $primaryKey = 'id'; set $incrementing = false for keys you assign.
  • Timestamps: created_at and updated_at are set on save; set $timestamps = false to turn this off.
  • Mass assignment: fill(), create() and update() only set attributes in $fillable (or not in $guarded, which blocks everything by default), and throw MassAssignmentException otherwise. forceFill() skips the check.
  • Casts: int, float, bool, string, array/json and datetime (a DateTimeImmutable).
  • Relations: hasMany, hasOne and belongsTo. Relation methods must declare their return type. Reading $post->comments loads them once; with('comments.author') eager-loads with one query per relation, and $post->load('comments') does it afterwards.
  • toArray() and json_encode() include loaded relations and leave out $hidden.

Schema

use ZiraPHP\Orm\Schema\Blueprint;

$schema = $connection->getSchemaBuilder();

$schema->create('posts', function (Blueprint $table): void {
    $table->id();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->string('title', 200);
    $table->string('slug')->unique();
    $table->text('body')->nullable();
    $table->boolean('published')->default(false)->index();
    $table->json('meta')->nullable();
    $table->timestamps();
});

$schema->table('posts', function (Blueprint $table): void {
    $table->integer('views')->default(0);
    $table->renameColumn('body', 'content');
    $table->dropIndex(['published']);
});

$schema->hasTable('posts');
$schema->hasColumn('posts', 'views');
$schema->dropIfExists('posts');

Column types: id, increments, bigIncrements, string, char, text, integer, bigInteger, smallInteger, unsignedInteger, unsignedBigInteger, boolean, decimal, float, date, dateTime, timestamp, time, json, uuid, binary and foreignId. Modifiers: nullable, default, useCurrent, unsigned, primary, unique, index. Table commands: index, unique, primary, foreign, dropColumn, renameColumn, dropIndex, dropUnique, dropForeign, dropConstrainedForeignId.

SQLite cannot add or drop foreign keys or add a primary key after a table is created; those calls throw SchemaException.

Migrations

Migration files live in database/migrations and are named YYYY_MM_DD_HHMMSS_description.php:

use ZiraPHP\Orm\Migration\Migration;
use ZiraPHP\Orm\Schema\Blueprint;
use ZiraPHP\Orm\Schema\Builder;

return new class extends Migration {
    public function up(Builder $schema): void
    {
        $schema->create('flights', function (Blueprint $table): void {
            $table->id();
            $table->string('number');
            $table->timestamps();
        });
    }

    public function down(Builder $schema): void
    {
        $schema->dropIfExists('flights');
    }
};
vendor/bin/zira make:migration create_flights_table
vendor/bin/zira make:migration add_gate_to_flights_table   # --table and --create also work
vendor/bin/zira migrate
vendor/bin/zira migrate:status
vendor/bin/zira migrate:rollback --step=2
vendor/bin/zira migrate:reset
vendor/bin/zira migrate:fresh --force                      # drops every table first

Each migrate run is one batch, and rollback undoes the last batch(es). On PostgreSQL and SQLite each migration runs in a transaction, so a failure leaves no half-applied schema; MySQL commits DDL immediately. Set public bool $withinTransaction = false; for statements that cannot run in a transaction, such as PostgreSQL's create index concurrently.

Without the console, use Migrator directly:

$migrator = new Migrator($connection, [__DIR__ . '/database/migrations']);
$migrator->run();
$migrator->rollback();

DataStoreInterface

PdoDataStore implements ZiraPHP's storage-agnostic DataStoreInterface (find, findBy, insert, update, delete) on a connection, so code written against the interface can move from InMemoryDataStore to a real database.

Development

composer check   # code style, PHPStan level 9, Psalm, PHPUnit

The MySQL and PostgreSQL tests run when ZIRA_TEST_MYSQL or ZIRA_TEST_PGSQL holds a DSN (credentials as user= and password= pairs). They drop every table in that database, so point them at a throwaway one:

ZIRA_TEST_PGSQL="pgsql:host=127.0.0.1;dbname=zira_test;user=zira;password=zira" vendor/bin/phpunit

License

MIT