Files

6.2 KiB

camelia/orm

Latest Stable Version Total Downloads License

Lightweight attribute-mapped Active Record ORM for MariaDB/MySQL over PDO.

  • Package: camelia/orm · Namespace: Camelia\Orm
  • PHP >=8.4, extensions pdo_mysql and mbstring
  • Runtime dependencies: psr/log (PSR-3, optional usage). brick/math is a suggestion for BigDecimal properties.

The contract lives in especificaciones-orm.md; this file only shows usage. The full developer guide, organised by task, is in docs/GUIA-PROGRAMADOR.md.

Install

composer require camelia/orm

Bootstrap

use Camelia\Orm\Orm;

$orm = Orm::fromArray([
    'host' => '127.0.0.1',
    'user' => 'app',
    'password' => 'secret',
    'database' => 'erp',
]);

// or from CAMELIA_DB_HOST, CAMELIA_DB_USER, CAMELIA_DB_NAME, CAMELIA_DB_PASS
$orm = Orm::fromEnv();

Declare a model

use Camelia\Orm\Attribute\{TableName, PrimaryKey, AutoIncrement, Guarded};
use Camelia\Orm\Model;

#[TableName('usuarios')]
final class Usuario extends Model
{
    #[PrimaryKey, AutoIncrement]
    public ?int $codigo = null;

    public string $nombre = '';

    #[Guarded]
    public string $passwordHash = '';
}

#[TableName] and exactly one #[PrimaryKey] are mandatory. A model that violates the rules throws MetadataException on first use instead of failing silently later.

Read

$repo = $orm->repository(Usuario::class);

$repo->find(['activo' => true], [['nombre', 'ASC']], limit: 20);
$repo->findFirst(['correo' => 'a@x']);
$repo->findByPk(5);
$repo->findByPkOrFail(5);          // throws RecordNotFoundException
$repo->count(['activo' => true]);
$repo->page(['activo' => true], [], page: 2, perPage: 25);

Fluent queries are immutable:

use Camelia\Orm\Query\{Cond, GroupCond};

$repo->query()
    ->where('activo', true)
    ->where('fecha', Cond::between('2024-01-01', '2024-12-31'))
    ->whereGroup(fn (GroupCond $g) => $g->or('correo', Cond::like('%@camelia.dev')))
    ->orderByDesc('fecha')
    ->with(['cliente.ciudad'])
    ->page(page: 1, perPage: 25);

Write

$repo->save($usuario);                  // INSERT or UPDATE, decided by the primary key
$repo->create(['nombre' => 'Ana']);     // new + hydrate + insert
$repo->update($usuario);                // always UPDATE, all writable columns
$repo->delete($usuario);
$repo->patch(5, ['nombre' => 'Bea']);   // partial update by primary key
$repo->remove(5);

update() writes the whole row. There is no dirty tracking: use patch() for partial updates. Writing a model hydrated through select() throws PartialModelException.

Transactions

$orm->transaction(function (Orm $orm) {
    $orm->repository(Usuario::class)->save($usuario);
});

Nested calls use savepoints and the original exception is rethrown.

Seeders

A seeder fills reference or bootstrap data and must be safe to run twice. The runner executes the batch inside one transaction, so a failure writes nothing.

final class PermissionsSeeder extends AbstractSeeder
{
    public function name(): string
    {
        return 'permissions';
    }

    public function run(Orm $orm): void
    {
        $repository = $orm->repository(PermissionModel::class);

        foreach (Permission::cases() as $permission) {
            $this->seedOnce($repository, ['code' => $permission->value], [
                'module' => $permission->module(),
                'action' => $permission->action(),
            ]);
        }
    }
}

$report = (new SeederRunner($orm))->addMany([new PermissionsSeeder()])->run();

Full guide in docs/SEEDING.md.

Command line

bin/camelia-orm ships the commands that need no knowledge of your code; the scaffolding commands write into the current directory, so run it from your project root.

vendor/bin/camelia-orm                  # list commands
vendor/bin/camelia-orm doctor            # check the connection from CAMELIA_DB_*
vendor/bin/camelia-orm make:model Invoice --table=invoices --dir=src/Models
vendor/bin/camelia-orm make:seeder RolesSeeder --dir=database/seeders
vendor/bin/camelia-orm seed --list
vendor/bin/camelia-orm seed --only=permissions,roles

seed runs whatever SeederRunner is wired to the command; the binary ships an empty runner, so an application registers its own seeders by composing SeedCommand into its own Application.

Errors

Every read and write throws on failure. Silent degradation to [] is deliberately absent: it hides connection failures as empty results. Catch DatabaseException (or DuplicateKeyException, ForeignKeyViolationException, LockTimeoutException) where degradation is genuinely intended.

Development

The toolchain is Mago plus PHPUnit and PHPStan.

composer install

composer fmt          # format with Mago
composer fmt:check    # CI: formatting must be clean
composer lint         # CI: Mago linter
composer analyze      # CI: Mago analyzer
composer phpstan      # CI: PHPStan level 8
composer test         # CI: PHPUnit

composer check        # runs the five gates above, in order
composer test:integration   # requires CAMELIA_TEST_DSN

The same gate runs on every commit once the hook is enabled per clone:

git config core.hooksPath .githooks

Use git commit --no-verify to bypass it for a single commit.

Configuration:

File Purpose
mago.toml formatter, linter, analyzer
mago-baseline.toml accepted analyzer findings (values coming from PDO)
phpstan.neon level 8, phpVersion: 80400
phpunit.xml.dist unit suite
phpunit.integration.xml.dist integration suite, skipped without CAMELIA_TEST_DSN

mago.toml pins php-version = "8.4", matching the minimum supported version, so mago fmt and the runtime agree on which syntax the package may ship.

License

MIT. See LICENSE.