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

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

greg-md/php-orm
===============

A powerful ORM(Object-Relational Mapping) for PHP.

21388↓100%2[1 issues](https://github.com/greg-md/php-orm/issues)[1 PRs](https://github.com/greg-md/php-orm/pulls)PHPCI passing

Since Jul 24Pushed 3mo ago4 watchersCompare

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

READMEChangelogDependenciesVersions (2)Used By (0)

Greg ORM
========

[](#greg-orm)

[![StyleCI](https://camo.githubusercontent.com/9b2dc503571101db2b779800d5a98870d810e4b6f6d281fba66073e879a73c27/68747470733a2f2f7374796c6563692e696f2f7265706f732f36363434313731392f736869656c643f7374796c653d666c6174)](https://styleci.io/repos/66441719)[![Build Status](https://camo.githubusercontent.com/7dcb9775cd186af44820b0bf0711ca92f0072770afeff6f6a02899245b3cf945/68747470733a2f2f7472617669732d63692e6f72672f677265672d6d642f7068702d6f726d2e737667)](https://travis-ci.org/greg-md/php-orm)[![Total Downloads](https://camo.githubusercontent.com/563c333931c38e67ad38851e9913dc2c48abec03476b33b7ab68ad7d903e988f/68747470733a2f2f706f7365722e707567782e6f72672f677265672d6d642f7068702d6f726d2f642f746f74616c2e737667)](https://packagist.org/packages/greg-md/php-orm)[![Latest Stable Version](https://camo.githubusercontent.com/7a78399e42245b84bd9ba5b346b759d96c75f3029a5c16ed17657f0266528618/68747470733a2f2f706f7365722e707567782e6f72672f677265672d6d642f7068702d6f726d2f762f737461626c652e737667)](https://packagist.org/packages/greg-md/php-orm)[![Latest Unstable Version](https://camo.githubusercontent.com/8409c03c762a49f7feb4c148995a51a7aefc451741c78d4f1c080437b0eaebdb/68747470733a2f2f706f7365722e707567782e6f72672f677265672d6d642f7068702d6f726d2f762f756e737461626c652e737667)](https://packagist.org/packages/greg-md/php-orm)[![License](https://camo.githubusercontent.com/65765b3b6a7a690445907d51e852b80e296c8960901939582e65c6aeda3ec3a7/68747470733a2f2f706f7365722e707567782e6f72672f677265672d6d642f7068702d6f726d2f6c6963656e73652e737667)](https://packagist.org/packages/greg-md/php-orm)

A lightweight but powerful ORM(Object-Relational Mapping) library for PHP.

[Gest Started](#get-started) with establishing a [Database Connection](#database-connection---quick-start), create an [Active Record Model](#active-record-model---quick-start) of a database table and write your first queries using the [Query Builder](#query-builder---quick-start).

Why use Greg ORM?
=================

[](#why-use-greg-orm)

You can read about it in the next article: *pending*

Get Started
===========

[](#get-started)

- [Requirements](#requirements)
- [Installation](#installation)
- [Supported Drivers](#supported-drivers)
- [Database Connection - Quick Start](#database-connection---quick-start)
- [Query Builder - Quick Start](#query-builder---quick-start)
- [Active Record Model - Quick Start](#active-record-model---quick-start)

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

[](#requirements)

- PHP Version `^7.1`

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

[](#installation)

You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):

`composer require greg-md/php-orm`

Supported Drivers
-----------------

[](#supported-drivers)

- **MySQL**
- **SQLite**

In progress:

- MS SQL
- PostgreSQL
- Oracle

Database Connection - Quick Start
---------------------------------

[](#database-connection---quick-start)

There are two ways of creating a database connection:

1. Instantiate a database connection for a specific driver;
2. Instantiate a connection manager to store multiple database connections.

> The connection manager implements the same connection strategy. This means that you can define a connection to act like it.

In the next example we will use a connection manager to store multiple connections of different drivers.

```
// Instantiate a Connection Manager
$manager = new \Greg\Orm\Connection\ConnectionManager();

// Register a MySQL connection
$manager->register('mysql_connection', function() {
    return new \Greg\Orm\Connection\MysqlConnection(
        new \Greg\Orm\Connection\Pdo('mysql:dbname=example_db;host=127.0.0.1', 'john', 'doe')
    );
});

// Register a SQLite connection
$manager->register('sqlite_connection', function() {
    return new \Greg\Orm\Connection\SqliteConnection(
        new \Greg\Orm\Connection\Pdo('sqlite:/var/db/example_db.sqlite')
    );
});

// Make the manager to act as "mysql_connection"
$manager->actAs('mysql_connection');
```

Now you can work with this manager:

```
// Fetch a statement from "sqlite_connection"
$manager->connection('sqlite_connection')
    ->select()
    ->from('Table')
    ->fetchAll();

// Fetch a statement from mysql_connection, which is used by default
$manager
    ->select()
    ->from('Table')
    ->fetchAll();
```

Full documentation can be found [here](docs/DatabaseConnection.md).

Active Record Model - Quick Start
---------------------------------

[](#active-record-model---quick-start)

The Active Record Model represents a table schema, an entity or a collection of entities of that table, integrated with the Query Builder to speed up your coding process.

Let's say you have `Users` table:

```
CREATE TABLE `Users` (
  `Id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `Email` VARCHAR(255) NOT NULL,
  `Password` VARCHAR(32) NOT NULL,
  `SSN` VARCHAR(32) NULL,
  `FirstName` VARCHAR(50) NULL,
  `LastName` VARCHAR(50) NULL,
  `Active` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1',
  PRIMARY KEY (`Id`),
  UNIQUE (`Email`),
  UNIQUE (`SSN`),
  KEY (`Password`),
  KEY (`FirstName`),
  KEY (`LastName`),
  KEY (`Active`)
);
```

Let's create the model for that table and configure it:

```
class UsersModel extends \Greg\Orm\Model
{
    // Define table alias. (optional)
    protected $alias = 'u';

    // Cast columns. (optional)
    protected $casts = [
        'Active' => 'boolean',
    ];

    // Table name (required)
    public function name(): string
    {
        return 'Users';
    }

    // Create abstract attribute "FullName". (optional)
    public function getFullNameAttribute(): string
    {
        return implode(' ', array_filter([$this['FirstName'], $this['LastName']]));
    }

    // Change "SSN" attribute. (optional)
    public function getSSNAttribute(): string
    {
        // Display only last 3 digits of the SSN.
        return str_repeat('*', 6) . substr($this['SSN'], -3, 3);
    }

    // Extend SQL Builder. (optional)
    public function whereIsNoFullName()
    {
        $this->whereIsNull('FirstName')->whereIsNull('LastName');

        return $this;
    }
}
```

Now, let's instantiate that model. The only thing you need is a [Database Connection](#database-connection---quick-start):

```
// Initialize the model.
$usersModel = new UsersModel($connection);
```

#### Working with table schema

[](#working-with-table-schema)

```
// Display table name.
print_r($usersModel->name()); // result: Users

// Display auto-increment column.
print_r($usersModel->autoIncrement()); // result: Id

// Display primary keys.
print_r($usersModel->primary()); // result: ['Id']

// Display all unique keys.
print_r($usersModel->unique()); // result: [['Email'], ['SSN']]
```

#### Working with a single row

[](#working-with-a-single-row)

```
// Create a user.
$user = $usersModel->create([
    'Email' => 'john@doe.com',
    'Password' => password_hash('secret'),
    'SSN' => '123456789',
    'FirstName' => 'John',
    'LastName' => 'Doe',
]);

// Display user email.
print_r($user['Email']); // result: john@doe.com

// Display user full name.
print_r($user['FullName']); // result: John Doe

print_r($user['SSN']); // result: ******789

// Display if user is active.
print_r($user['Active']); // result: true

// Display user's primary keys.
print_r($user->getPrimary()); // result: ['Id' => 1]
```

#### Working with a row set

[](#working-with-a-row-set)

```
// Create some users.
$usersModel->create([
   'Email' => 'john@doe.com',
   'Password' => password_hash('secret'),
   'Active' => true,
]);

$usersModel->create([
   'Email' => 'matt@damon.com',
   'Password' => password_hash('secret'),
   'Active' => false,
]);

$usersModel->create([
   'Email' => 'josh@barro.com',
   'Password' => password_hash('secret'),
   'Active' => false,
]);

// Fetch all inactive users from database.
$inactiveUsers = $usersModel->whereIsNot('Active')->fetchAll();

// Display users count.
print_r($inactiveUsers->count()); // result: 2

// Display users emails.
print_r($inactiveUsers->get('Email')); // result: ['matt@damon.com', 'josh@barro.com']

// Activate all users in the row set.
$inactiveUsers->set('Active', true)->save();

print_r($inactiveUsers[0]['Active']); // result: true
print_r($inactiveUsers[1]['Active']); // result: true
```

#### Working with Query Builder

[](#working-with-query-builder)

Select users that doesn't have first and last names.

```
$users = $usersModel
    ->whereIsNoFullName()
    ->orderAsc('Id')
    ->fetchAll();
```

Update an user:

```
$usersModel
    ->where('Id', 10)
    ->update(['Email' => 'foo@bar.com']);
```

Full documentation can be found [here](docs/ActiveRecordModel.md).

Query Builder - Quick Start
---------------------------

[](#query-builder---quick-start)

The Query Builder provides an elegant way of creating SQL statements and clauses on different levels of complexity.

You can easily instantiate a Query Builder with a [Database Connection](#database-connection---quick-start).

Let's say you have `Students` table.

Find students names that lives in Chisinau and were born in 1990:

```
$students = $connection->select()
    ->columns('Id', 'Name')
    ->from('Students')
    ->where('City', 'Chisinau')
    ->whereYear('Birthday', 1990)
    ->fetchAll();
```

Update the grade of a student:

```
$connection->update()
    ->table('Students')
    ->set('Grade', 1400)
    ->where('Id', 10)
    ->execute();
```

Delete students that were not admitted in the current year:

```
$connection->delete()
    ->from('Students')
    ->whereIsNot('Admitted')
    ->execute();
```

Add a new student:

```
$query = $connection->insert()
    ->into('Students')
    ->data(['Name' => 'John Doe', 'Year' => 2017])
    ->execute();
```

Full documentation can be found [here](docs/QueryBuilder.md).

Documentation
=============

[](#documentation)

- [Database Connection](docs/DatabaseConnection.md)
- [Active Record Model](docs/ActiveRecordModel.md)
- [Query Builder](docs/QueryBuilder.md)
- **Migrations** are under construction, but you can use [Phinx](https://phinx.org/) in the meantime.

License
=======

[](#license)

MIT © [Grigorii Duca](http://greg.md)

*Huuuge Quote*
==============

[](#huuuge-quote)

[![I fear not the man who has practiced 10,000 programming languages once, but I fear the man who has practiced one programming language 10,000 times. © #horrorsquad](https://camo.githubusercontent.com/73fc580403a8367b075fff0a0d7439dc0dc095dd3124b22757522675c1308df8/687474703a2f2f677265672e6d642f6875757567652d71756f74652d66622e6a7067)](https://camo.githubusercontent.com/73fc580403a8367b075fff0a0d7439dc0dc095dd3124b22757522675c1308df8/687474703a2f2f677265672e6d642f6875757567652d71756f74652d66622e6a7067)

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance53

Moderate activity, may be stable

Popularity23

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity38

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/85a6700372326d0546fcff3eb2c3f27daa711273bdd5d6fdda875a7d2f02af85?d=identicon)[greg-md](/maintainers/greg-md)

---

Top Contributors

[![greg-md](https://avatars.githubusercontent.com/u/10551984?v=4)](https://github.com/greg-md "greg-md (82 commits)")

---

Tags

activerecordbig-datagreg-mdgreg-phpintellisensemigrationsmssqlmysqloracleormphpphp-ormpostgresqlquery-buildersqliteweb-artisans

### Embed Badge

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

```
[![Health](https://phpackages.com/badges/greg-md-php-orm/health.svg)](https://phpackages.com/packages/greg-md-php-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.3k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M543](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M209](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

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

PHPackages © 2026

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