PHPackages                             parable-php/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. parable-php/orm

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

parable-php/orm
===============

Parable ORM is a small but complete repository-pattern ORM implementation

1.0.0(5y ago)3512↓100%[1 issues](https://github.com/parable-php/orm/issues)1MITPHPPHP &gt;=8.0

Since Mar 9Pushed 5y ago1 watchersCompare

[ Source](https://github.com/parable-php/orm)[ Packagist](https://packagist.org/packages/parable-php/orm)[ Docs](https://github.com/parable-php/orm)[ RSS](/packages/parable-php-orm/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (25)Used By (1)

Parable ORM
===========

[](#parable-orm)

[![Workflow Status](https://github.com/parable-php/orm/workflows/Tests/badge.svg)](https://github.com/parable-php/orm/actions?query=workflow%3ATests)[![Latest Stable Version](https://camo.githubusercontent.com/8690be7050ffee7cfc9f96c245e723ec48ab3eb56326678f67662fd849408b51/68747470733a2f2f706f7365722e707567782e6f72672f70617261626c652d7068702f6f726d2f762f737461626c65)](https://packagist.org/packages/parable-php/orm)[![Latest Unstable Version](https://camo.githubusercontent.com/c4a44eb63d4d35a4f4f78668c09c3cec5ead4abceef4e53c99b4eb378b10846c/68747470733a2f2f706f7365722e707567782e6f72672f70617261626c652d7068702f6f726d2f762f756e737461626c65)](https://packagist.org/packages/parable-php/orm)[![License](https://camo.githubusercontent.com/7557b9b9bc81908eeb91135bc18ebc8603a8c66d713d5cf238c9d8a6c18c8dc9/68747470733a2f2f706f7365722e707567782e6f72672f70617261626c652d7068702f6f726d2f6c6963656e7365)](https://packagist.org/packages/parable-php/orm)

Parable ORM is a light-weight repository-pattern based ORM.

Install
-------

[](#install)

Php 8.0+ and [composer](https://getcomposer.org) are required.

```
$ composer require parable-php/orm
```

Usage
-----

[](#usage)

Repositories are used to find, save and delete entities, which represent rows from your MySQL/Sqlite database. Parable ORM attempts to combine queries to be as efficient as possible.

Entities are relatively straight-forward PHP data objects, and are expected to offer setters and getters for all values associated with that entity. Example:

```
class Entity extends AbstractEntity {
    protected $id;
    protected $name;

    // We int cast because we know it is an int
    public function getId(): int {
        return (int)$this->id;
    }

    public function setName(string $name): void {
        $this->name = $name;
    }

    public function getName(): ?string {
        return $this->name;
    }
}
```

As you can see, the entity itself doesn't really need much. The Repository set up for this entity type, however, will contain some metadata so it knows how to handle them.

If you want to support automatic setting of a `created at` or `updated at` value, it's as simple as implementing either the `SupportsCreatedAt` or `SupportsUpdatedAt` interfaces. The repository will automatically pick up on it and attempt to call `markCreatedAt()` or `markUpdatedAt()`, leaving the specific property/column names up to you. Example:

```
class Entity extends AbstractEntity implements SupportsCreatedAt {
    protected $id;
    protected $created_at;

    // We int cast because we know it is an int
    public function getId(): int {
        return (int)$this->id;
    }

    public function getCreatedAt(): ?string {
        return $this->created_at;
    }

    public function setCreatedAt(string $createdAt): void {
        $this->created_at = $createdAt;
    }

    // Only this method is defined on the interface
    public function markCreatedAt(): void {
        $this->setCreatedAt((new DateTimeImmutable())->format(Database::DATETIME_SQL));
    }
}
```

Here's the Repository to handle the above Entity:

```
class EntityRepository extends AbstractRepository {
    public function getTableName(): string {
        return 'entity';
    }

    public function getPrimaryKey(): string {
        return 'id';
    }

    public function getEntityClass(): string {
        return Entity::class;
    }
}
```

As mentioned, both entities and repositories are intended to be as simple and straightforward as possible. Entities and Repositories use `parable-php/di`, meaning they can use constructor-based injected dependencies.

#### Basic Repository use

[](#basic-repository-use)

```
$repository->findAll(); // returns AbstractEntity[]
```

```
$repository->countAll(); // returns int
```

```
$repository->find(23); // returns ?AbstractEntity
```

#### Condition-based repository use

[](#condition-based-repository-use)

For advanced (and possibly complex) where conditions, we use a `callable` which is given a properly set up `Query` object. This allows for fine-grained control with a very low barrier to do so.

```
$repository->findBy(function (Query $query) {
    $query->where('name', '=', 'First-name');
    $query->whereNotNull('activated_at');
    $query->whereCallable(function (Query $query) {
        $query->where('test_value', '=', '1');
        $query->orWhere('test_value', '=', '4');
    });
});
```

This ends up building the following query:

```
SELECT * FROM `entity`
WHERE (
    `entity`.`name` = 'First-name'
    AND `entity`.`activated_at` IS NOT NULL
    AND (
        `entity`.`test_value` = '1'
        OR `entity`.`test_value` = '4'
    )
);
```

The methods `where`, `whereNull`, `whereNotNull` and `whereCallable` will use `AND` to combine the clauses. To do otherwise, all have an `or`-version. `orWhere`, `orWhereNull`, `orWhereNotNull`, `orWhereCallable`, and by using those specifically, an `OR` clause can be created.

In many cases you'll want to either only use `or`-clauses, or, to use an `OR` clause in an otherwise `AND`-oriented where list, use a `callable` to make sure they're grouped appropriately.

#### Saving and deleting entities

[](#saving-and-deleting-entities)

To save an entity, simply tell the repository to do so:

```
$savedEntity = $repository->save($entity);
```

Or save multiple:

```
$savedEntities = $repository->saveAll($entity1, $entity2, $entity3);
```

You can also easily defer a save, so that the entity is prepared for a save but not actually saved until you decide to do so. When this is done, all entities that need to be updated are saved individually as they are found in the deferred save list, but all entities that are new (aka to be `INSERT`ed) are combined into a single `INSERT` query instead.

```
foreach ($newEntities as $entity) {
    $repository->deferSave($entity);
}
// OR:
$repository->deferSave(...$newEntities);

$repository->saveDeferred(); // returns nothing
```

If `$newEntities` contains 10 entities that are all new, one query will now insert all 10 in one go. If, for example, `$newEntities` contains 5 new and 5 pre-existing entities, `saveDeferred` will build the single `INSERT` query for the 5 new ones, and as it comes across them, save the updates immediately.

Deleting works the same:

```
$repository->delete($entity); // Single
$repository->delete($entity1, $entity2); // Multiple, just keep adding
$repository->delete(...$entities); // Splats for the win
```

And deferred deletes are also possible, and will attempt to delete all deferred entities in a single query:

```
$repository->deferDelete($entity); // Single
$repository->deferDelete($entity1, $entity2); // Multiple, just keep adding
$repository->deferDelete(...$entities); // Splats for the win

$repository->deleteDeferred(); // Actually perform it.
```

For both deferred saves and deletes, the currently stored entities to be saved or deleted can be cleared by calling either `clearDeferredSaves()` or `clearDeferredDeletes()`.

#### How to connect to a database

[](#how-to-connect-to-a-database)

You didn't think I'd ever forget this, do you? 2 database types are currently supported, MySQL and Sqlite3.

To connect to a MySQL server:

```
$database = new Database(
    Database::TYPE_MYSQL,
    'parable',
    'localhost',
    'username',
    'password'
);
```

Or:

```
$database = new Database();
$database->setDatabaseName('parable');
$database->setHost('localhost');
$database->setUsername('username');
$database->setPassword('password');

$database->connect();

$results = $database->query('SELECT * FROM users');
```

And to connect to a Sqlite3 file:

```
$database = new Database(
    Database::TYPE_SQLITE,
    'storage/parable.db'
);
```

Or:

```
$database = new Database();
$database->setDatabaseName('storage/parable.db');

$database->connect();

$results = $database->query('SELECT * FROM users');
```

Contributing
------------

[](#contributing)

Any suggestions, bug reports or general feedback is welcome. Use github issues and pull requests, or find me over at [devvoh.com](https://devvoh.com).

License
-------

[](#license)

All Parable components are open-source software, licensed under the MIT license.

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance13

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity75

Established project with proven stability

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 ~32 days

Recently: every ~12 days

Total

24

Last Release

1893d ago

Major Versions

0.11.1 → 1.0.02021-03-12

PHP version history (2 changes)0.1.0PHP &gt;=7.1

0.10.0PHP &gt;=8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/7db40df70c77a9d591de4521642b0ddcb6c448e4876b22dc2f76900c736ab579?d=identicon)[robindevoh](/maintainers/robindevoh)

---

Tags

databaselibraryormparablephp8repositorymicrodatabaselibraryormparable

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/parable-php-orm/health.svg)

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

###  Alternatives

[rah/danpu

Zero-dependency MySQL dump library for easily exporting and importing databases

64401.8k10](/packages/rah-danpu)[bephp/activerecord

micro activerecord library in PHP(only 400 lines with comments), support chain calls and relations(HAS\_ONE, HAS\_MANY, BELONGS\_TO).

1202.1k2](/packages/bephp-activerecord)[friendsofsymfony1/doctrine1

PHP Database ORM for Symfony1. Do NOT use for new projects: please move to a newest Symfony release and Doctrine2

40581.8k](/packages/friendsofsymfony1-doctrine1)[andsalves/doctrine-elastic

Elasticsearch Doctrine Adaptation

156.6k](/packages/andsalves-doctrine-elastic)[flightphp/active-record

Micro Active Record library in PHP, support chain calls, events, and relations.

163.0k](/packages/flightphp-active-record)[icanboogie/activerecord

ActiveRecord Object-relational mapping

135.0k3](/packages/icanboogie-activerecord)

PHPackages © 2026

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