PHPackages                             compositephp/db - 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. compositephp/db

ActiveLibrary

compositephp/db
===============

PHP 8.1+ DataMapper and Table Gateway

v0.5.0(9mo ago)82382↓100%3[1 issues](https://github.com/compositephp/db/issues)MITPHPPHP ^8.1CI passing

Since Oct 20Pushed 9mo ago2 watchersCompare

[ Source](https://github.com/compositephp/db)[ Packagist](https://packagist.org/packages/compositephp/db)[ RSS](/packages/compositephp-db/feed)WikiDiscussions master Synced today

READMEChangelog (8)Dependencies (7)Versions (17)Used By (0)

What is Composite DB
====================

[](#what-is-composite-db)

[![Latest Stable Version](https://camo.githubusercontent.com/a4736e69448db286c25918a6012cc1cd101e2531649255010d14230130a3b3ba/68747470733a2f2f706f7365722e707567782e6f72672f636f6d706f736974657068702f64622f762f737461626c65)](https://packagist.org/packages/compositephp/db)[![Build Status](https://github.com/compositephp/db/actions/workflows/main.yml/badge.svg)](https://github.com/compositephp/db/actions)[![Codecov](https://camo.githubusercontent.com/f11b916694a9751cb80ac93649515b59bef81d8b957f0cd359473c39c6a35f8d/68747470733a2f2f636f6465636f762e696f2f67682f636f6d706f736974657068702f64622f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/compositephp/db/)

Composite DB is lightweight and fast PHP DataMapper and Table Gateway which allows you to represent your SQL tables scheme in OOP style using full power of PHP 8.1+ class syntax.

It also gives you CRUD, query builder and automatic caching out of the box, so you can start to work with your database from php code in a minutes!

Overview:

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Quick example](#quick-example)
- [Documentation](doc/README.md)

Features
--------

[](#features)

- **Lightweight** - easier entity schema, no getters and setters, you don't need attributes for each column definition, just use native php class syntax.
- **Speed** - it's 1.5x faster in pure SQL queries mode and many times faster in automatic caching mode (see [benchmark](https://github.com/compositephp/php-orm-benchmark)).
- **Easy caching** - gives you CRUD operations caching out of the box and in general it's much easier to work with cached "selects".
- **Strict types** - Composite DB forces you to be more strict typed and makes your IDE happy.
- **Hydration** - you can serialize your Entities to plain array or json and deserialize them back.
- **Flexibility** - gives you more freedom to extend Repositories, for example it's easier to build sharding tables.
- **Code generation** - you can generate Entity and Repository classes from your SQL tables.
- **Division of responsibility** - every Entity has its own Repository class, and it's the only entry point to make queries to your table.

It also has many popular features such as:

- **Query Builder** - build your queries with constructor, based on [doctrine/dbal](https://github.com/doctrine/dbal)
- **Migrations** - synchronise your php entities with database tables

Requirements
------------

[](#requirements)

- PHP 8.1+
- PDO Extension with desired database drivers

Installation
------------

[](#installation)

1. Install package via composer: ```
    $ composer require compositephp/db
    ```
2. Configure `Composite\DB\ConnectionManager` ([example](./doc/configuration.md#configure-connectionmanager))
3. (Optional) Configure [symfony/console](https://symfony.com/doc/current/components/console.html#creating-a-console-application)commands to use automatic class generators ([example](./doc/configuration.md#configure-console-commands))
4. (Optional) Install and configure any PSR-16 (simple cache) package to use automatic caching

Quick example
-------------

[](#quick-example)

Imagine you have simple table `Users`

```
create table Users
(
    `id`         int auto_increment,
    `email`      varchar(255)                                         not null,
    `name`       varchar(255)               default NULL              null,
    `is_test`    tinyint(1)                 default 0                 not null,
    `languages`  json                       default '[]'              not null,
    `status`     enum ("ACTIVE", "BLOCKED") default "ACTIVE"          null,
    `created_at` TIMESTAMP                  default CURRENT_TIMESTAMP not null,
    constraint Users_pk primary key (id)
);
```

First, you need to do is to execute command to generate php entity:

```
$ php console.php composite-db:generate-entity dbName Users 'App\User'
```

New entity class `User` and enum `Status` will be automatically generated:

```
#[Table(db: 'dbName', name: 'Users')]
class User extends AbstractEntity
{
    #[PrimaryKey(autoIncrement: true)]
    public readonly int $id;

    public function __construct(
        public string $email,
        public ?string $name = null,
        public bool $is_test = false,
        public array $languages = [],
        public Status $status = Status::ACTIVE,
        public readonly \DateTimeImmutable $created_at = new \DateTimeImmutable(),
    ) {}
}
```

```
enum Status
{
    case ACTIVE;
    case BLOCKED;
}
```

Second step, is to generate a table class (repository) for your entity:

```
$ php console.php composite-db:generate-table 'App\User' 'App\UsersTable'
```

And that's it, now you have CRUD for your SQL table and simple selects:

```
$table = new UsersTable();

//Create
$user = new User(
    email: 'user@example.com',
    name: 'John',
    languages: ['en', 'fr'],
);
$table->save($user);

//Read
$user = $table->findByPk(123);

//Update
$user->status = Status::BLOCKED;
$table->save($user);

//Delete
$table->delete($user);

//Other selects out of the box
$table->findAll();
$table->countAll();
```

> You can find full working example [here](doc/example.md) which you can copy and run as is.

You can also serialize user entity to array or json:

```
var_export($user->toArray());

//will output
array (
  'id' => 123,
  'email' => 'user@example.com',
  'name' => 'John',
  'is_test' => false,
  'languages' => '["en","fr"]',
  'status' => 'BLOCKED',
  'created_at' => '2022-01-01 11:22:33.000000',
)
```

Or deserialize (hydrate) entity from array:

```
$user = User::fromArray([
  'id' => 123,
  'email' => 'user@example.com',
  'name' => 'John',
  'is_test' => false,
  'languages' => '["en","fr"]',
  'status' => 'BLOCKED',
  'created_at' => '2022-01-01 11:22:33.000000',
]);
```

And that's it, no special getters or setters, no "behaviours" or extra code, smart entity casts everything automatically. More about Entity and supported auto casting types you can find [here](doc/entity.md).

License:
--------

[](#license)

MIT License (MIT). Please see [`LICENSE`](./LICENSE) for more information. Maintained by Composite PHP.

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance56

Moderate activity, may be stable

Popularity27

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~73 days

Recently: every ~140 days

Total

14

Last Release

291d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/585d414228f543dd8e3eb606f05a4b7bd52388a671abb52b70cc5bad4f7d1739?d=identicon)[compositephp](/maintainers/compositephp)

---

Top Contributors

[![compositephp](https://avatars.githubusercontent.com/u/38870693?v=4)](https://github.com/compositephp "compositephp (68 commits)")

---

Tags

databasedatamapperdoctrineentityfasthydrationlightweightmysqlphpphp81posgresqlsqlitetablegateway

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/compositephp-db/health.svg)

```
[![Health](https://phpackages.com/badges/compositephp-db/health.svg)](https://phpackages.com/packages/compositephp-db)
```

###  Alternatives

[jackalope/jackalope-doctrine-dbal

Jackalope Transport library for Doctrine DBAL

1512.9M185](/packages/jackalope-jackalope-doctrine-dbal)[oro/platform

Business Application Platform (BAP)

648132.0k71](/packages/oro-platform)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

605.0M332](/packages/shopware-core)[neos/flow

Flow Application Framework

862.0M395](/packages/neos-flow)[neos/flow-development-collection

Flow packages in a joined repository for pull requests.

144177.1k1](/packages/neos-flow-development-collection)[oat-sa/generis

TAO generis library

10137.4k62](/packages/oat-sa-generis)

PHPackages © 2026

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