PHPackages                             byjg/micro-orm - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. byjg/micro-orm

ActiveLibrary[Database &amp; ORM](/categories/database)

byjg/micro-orm
==============

A micro framework for create a very simple decoupled ORM. This library intended to be very small and very simple to use

6.0.0(5mo ago)2048.5k↓44%36MITPHPPHP &gt;=8.3 &lt;8.6CI passing

Since Jun 22Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/byjg/php-micro-orm)[ Packagist](https://packagist.org/packages/byjg/micro-orm)[ GitHub Sponsors](https://github.com/byjg)[ RSS](/packages/byjg-micro-orm/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (31)Used By (6)

   sidebar\_key micro-orm   tags    php

 databases

 orm

    MicroOrm for PHP
================

[](#microorm-for-php)

A micro framework for create a very simple decoupled ORM. This library intended to be very small and very simple to use;

[![Sponsor](https://camo.githubusercontent.com/fab14b7f7f475072ada0473f193d6f322561fd4a2958e0cc89910d053347cf27/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f53706f6e736f722d2532336561346161613f6c6f676f3d67697468756273706f6e736f7273266c6f676f436f6c6f723d7768697465266c6162656c436f6c6f723d306431313137)](https://github.com/sponsors/byjg)[![Build Status](https://github.com/byjg/php-micro-orm/actions/workflows/phpunit.yml/badge.svg?branch=master)](https://github.com/byjg/php-micro-orm/actions/workflows/phpunit.yml)[![Opensource ByJG](https://camo.githubusercontent.com/425c1bbccc0f292bf4d20569ae74a6b2e384fd648f1af8911bc61de9a8dcfc0b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6f70656e736f757263652d62796a672d737563636573732e737667)](http://opensource.byjg.com)[![GitHub source](https://camo.githubusercontent.com/88e61eb211719144efdd570290a0456b6e13099c2df8d973f1bb43fe33bf0039/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4769746875622d736f757263652d696e666f726d6174696f6e616c3f6c6f676f3d676974687562)](https://github.com/byjg/php-micro-orm/)[![GitHub license](https://camo.githubusercontent.com/045559f25b9a2d25231889793df4cc953186b2265b00f9f4aeab52a12f035cd4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f62796a672f7068702d6d6963726f2d6f726d2e737667)](https://opensource.byjg.com/opensource/licensing.html)[![GitHub release](https://camo.githubusercontent.com/b208ba2f8532718439f537a7c4ab1fb84f6d6f2f98f52140428c8a134054e5a1/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f62796a672f7068702d6d6963726f2d6f726d2e737667)](https://github.com/byjg/php-micro-orm/releases/)

Key Features:

- Can be used with any DTO, Entity, Model or whatever class with public properties or with getter and setter
- The repository support a variety of datasources: MySql, Sqlite, Postgres, MySQL, Oracle (see byjg/anydataset)
- A class Mapper is used for mapping the Entity and the repository
- Powerful mapper functions for automatic data transformation between models and database
- Small and simple to use

Architecture
------------

[](#architecture)

MicroORM implements **Martin Fowler's enterprise patterns**:

- **[Repository](https://martinfowler.com/eaaCatalog/repository.html)**: Mediates between domain and data mapping layers
- **[Data Mapper](https://martinfowler.com/eaaCatalog/dataMapper.html)**: Separates domain objects from database tables
- **[Active Record](https://martinfowler.com/eaaCatalog/activeRecord.html)**: Wraps database rows with domain logic ( alternative approach)

You can choose the pattern that best fits your application: use Repository + Data Mapper for complex domains, or Active Record for simpler CRUD-focused applications.

These are the key components:

```
┌──────────────────────────┐
│ Repository               │              ┌─────────────────────┐
│                          │         ┌────│        Model        │
│                          │         │    └─────────────────────┘
│          ┌───────────────┴─────┐   │               │
│          │       Mapper        │───┤               │
│          └───────────────┬─────┘   │               │
│                     │    │         │    ┌─────────────────────┐
│                     │    │         └────│    FieldMapping     │
│                     │    │              └─────────────────────┘
│                     │    │
│          ┌───────────────┴─────┐
│          │        Query        │
│          └───────────────┬─────┘
│                     │    │
│          ┌───────────────┴─────┐        ┌──────────────────────┐
│          │  DatabaseExecutor   │────────│   DbDriverInterface  │
│          └───────────────┬─────┘        └────────────┬─────────┘
│                          │                           │
└──────────────────────────┘                      .─────────.
                                                 │           │
                                                 │`─────────'│
                                                 │           │
                                                 │    DB     │
                                                 │           │
                                                 │           │
                                                  `─────────'

```

- **Model** can be any class with public properties or with getter and setter. It is used to retrieve or save the data into the database
- **Mapper** defines the relationship between the Model properties and the database fields
- **FieldMapping** defines individual field mappings within the Mapper (field names, transformations, relationships via `parentTable`)
- **Query** defines what to retrieve from/update in the database. It uses the Mapper to prepare the query to the database converting the Model properties to database fields
- **DatabaseExecutor** (external package) wraps the DbDriver and provides transaction management, query execution, and access to database helpers
- **DbDriverInterface** (external package) is the actual database driver implementation that connects to the database
- **Repository** orchestrates all MicroORM components and uses DatabaseExecutor to interact with the database

For a detailed explanation of the architecture and when to use each layer, see [Architecture Layers: Infrastructure vs Domain](docs/architecture-layers.md).

Getting Started
---------------

[](#getting-started)

### Table Structure

[](#table-structure)

We have the following table structure in the database for this example:

```
CREATE TABLE `mytable` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `company_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```

We want to be able to interact with this table using the ORM.

### Defining the Model

[](#defining-the-model)

A Model in our context is a class that symbolizes the data you wish to store or fetch from the database. This Model class can be as simple as a class with public properties. Alternatively, it can be a class equipped with getter and setter methods for more controlled access and manipulation of the data.

To map the database fields, you can add attributes to the Model class. Each property in the Model class represents a field in the database.

Let's look at an example:

```
#[TableAttribute(tableName: 'mytable')]
class MyModel
{
    #[FieldAttribute(primaryKey: true)]
    public ?int $id = null;

    #[FieldAttribute()]
    public ?string $name = null;

    #[FieldAttribute(fieldName: 'company_id')
    public ?int $companyId = null;
}
```

In this example, we have a class `MyModel` with three properties: `id`, `name`, and `companyId`.

- The `id` property is marked as a primary key.
- The `name` property is a simple field.
- The `companyId` property is a field with a different name in the database `company_id`.

The `TableAttribute` is used to define the table name in the database.

### Connecting the repository

[](#connecting-the-repository)

After defining the Model, you can connect the Model with the repository.

```
$dbDriver = \ByJG\AnyDataset\Db\Factory::getDbInstance('mysql://user:password@server/schema');
$repository = new \ByJG\MicroOrm\Repository($dbDriver, MyModel::class);
```

### Querying the database

[](#querying-the-database)

You can query the database using the repository.

```
$myModel = $repository->get(1);
```

or

```
$query = Query::getInstance()
    ->field('name')
    ->where('company_id = :cid', ['cid' => 1]);

$result = $repository->getByQuery($query);
```

or, the same example above:

```
$filterModel = $repository->entity([
    'company_id' => 1
]);

$query = $repository->queryInstance($filterModel);
$query->field('name');

$result = $repository->getByQuery($query);
```

Basics
------

[](#basics)

- [Defining the Model](docs/getting-started-model.md)
- [Querying the Database](docs/querying-the-database.md)
- [Updating the database](docs/updating-the-database.md)
- [Using the Mapper Object](docs/using-mapper-object.md)
- [The Model Attributes](docs/model-attribute.md)
- [The Repository Class](docs/repository.md)
- [Common Traits for Timestamp Fields](docs/common-traits.md)
- [Architecture Layers: Infrastructure vs Domain](docs/architecture-layers.md)
- [Comparison with Other ORMs (Eloquent, Doctrine)](docs/comparison-with-other-orms.md)

Advanced Topics
---------------

[](#advanced-topics)

- [Active Record](docs/active-record.md)
- [Auto Discovering Relationship](docs/auto-discovering-relationship.md)
- [The Literal Object](docs/the-literal-object.md)
- [Soft Delete](docs/softdelete.md)
- [Caching the Results](docs/cache.md)
- [Observing the Database](docs/observers.md)
- [Controlling the data queried/updated](docs/controlling-the-data.md)
- [Mapper Functions](docs/mapper-functions.md)
- [Using FieldAlias](docs/using-fieldalias.md)
- [Tables without auto increments fields](docs/tables-without-auto-increment-fields.md)
- [Using With Recursive SQL Command](docs/using-with-recursive-sql-command.md)
- [QueryRaw (raw SQL)](docs/query-raw.md)
- [Update Constraints](docs/update-constraints.md)
- [Building SQL Queries](docs/query-build.md)
- [UUID Support](docs/uuid-support.md)

Install
-------

[](#install)

Just type:

```
composer require "byjg/micro-orm"
```

Running Tests
-------------

[](#running-tests)

```
./vendor/bin/phpunit
```

Related Projects
----------------

[](#related-projects)

- [Database Migration](https://github.com/byjg/migration)
- [Anydataset](https://github.com/byjg/anydataset)
- [PHP Rest Template](https://github.com/byjg/php-rest-template)
- [USDocker](https://github.com/usdocker/usdocker)
- [Serializer](https://github.com/byjg/serializer)

Dependencies
------------

[](#dependencies)

 ```
flowchart TD
    byjg/micro-orm --> byjg/anydataset-db
    byjg/micro-orm --> ext-json
```

      Loading ---

[Open source ByJG](http://opensource.byjg.com)

###  Health Score

61

—

FairBetter than 99% of packages

Maintenance79

Regular maintenance activity

Popularity38

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity91

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 97.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~118 days

Recently: every ~20 days

Total

30

Last Release

174d ago

Major Versions

1.0.1 → 2.0.02017-05-27

2.2.2 → 4.0.02018-11-24

4.9.4 → 5.0.02024-10-29

5.0.8 → 6.0.02025-11-25

PHP version history (5 changes)1.0.0PHP &gt;=5.5.0

2.2.1PHP &gt;=5.6.0

4.9.1PHP &gt;=7.4

5.0.0PHP &gt;=8.1 &lt;8.4

6.0.0PHP &gt;=8.3 &lt;8.6

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/981924?v=4)[Joao Gilberto Magalhaes](/maintainers/byjg)[@byjg](https://github.com/byjg)

---

Top Contributors

[![byjg](https://avatars.githubusercontent.com/u/981924?v=4)](https://github.com/byjg "byjg (313 commits)")[![HilarioJrx](https://avatars.githubusercontent.com/u/162637964?v=4)](https://github.com/HilarioJrx "HilarioJrx (9 commits)")

---

Tags

byjgentitymicro-frameworkmysqlmysql-ormormsqlite3sqlserver

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/byjg-micro-orm/health.svg)

```
[![Health](https://phpackages.com/badges/byjg-micro-orm/health.svg)](https://phpackages.com/packages/byjg-micro-orm)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90440.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)[wildside/userstamps

Laravel Userstamps provides an Eloquent trait which automatically maintains `created\_by` and `updated\_by` columns on your model, populated by the currently authenticated user in your application.

7511.7M13](/packages/wildside-userstamps)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
