PHPackages                             graze/dal - 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. graze/dal

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

graze/dal
=========

Data Access Layer

v0.1.1(10y ago)814.5k↓50%[2 issues](https://github.com/graze/dal/issues)MITPHPPHP &gt;=5.4.0

Since Jul 8Pushed 6y ago15 watchersCompare

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

READMEChangelog (9)Dependencies (10)Versions (15)Used By (0)

DAL (Data Access Layer)
=======================

[](#dal-data-access-layer)

[![Graze.com](diagram.png)](diagram.png)

![Travis branch](https://camo.githubusercontent.com/12ac8906ddf3d850d2cf50093bc98e501179eb1ebc914ced54117372a2b9d53c/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f6772617a652f64616c2f6d61737465722e7376673f7374796c653d666c61742d737175617265)![Scrutinizer](https://camo.githubusercontent.com/0bcd3c97e945fecd418931eb39a14a80812c4d9cf7202ae69ce05b25690f1e26/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f6772617a652f64616c2e7376673f7374796c653d666c61742d737175617265)![Scrutinizer Coverage](https://camo.githubusercontent.com/50c7dddcb5bfeab12be44bd947748d0ff84e6a99e03792f7ae87594e8353f99e/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f636f7665726167652f672f6772617a652f64616c2e7376673f7374796c653d666c61742d737175617265)![PHP Version](https://camo.githubusercontent.com/bcf32f3de6e309cd1ab15ea5873710eee52ea7fc7fefb226162356791a70afca/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d2533453d352e352d626c75652e7376673f7374796c653d666c61742d737175617265)![Packagist](https://camo.githubusercontent.com/6a677ba2c76d4704a5279376f6b3ea52f4e4a6541fbf848b1610a8ff4d6d3a89/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6772617a652f64616c2e7376673f7374796c653d666c61742d737175617265)![Packagist](https://camo.githubusercontent.com/e98f905cb23878d74b1ff073f1833f4ce919b428f093404febbdd36dd621679d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6772617a652f64616c2e7376673f7374796c653d666c61742d737175617265)

**DAL** is a data access layer for PHP, built to add an additional layer of abstraction between your application and persistence layers. The main goal of this library is to allow use of multiple persistence layers, each potentially employing different abstraction patterns, under a *single* interface.

The [data mapper pattern](http://en.wikipedia.org/wiki/Data_mapper_pattern) is great for keeping the particulars of data persistence hidden behind its interfaces. DAL improves upon this abstraction to include multiple persistence layers while providing underlying support for patterns other than data mapper (e.g. [active record](http://en.wikipedia.org/wiki/Active_record_pattern)).

We're using this in-house to move our application towards a more manageable data mapper layer rather than our current active record implementation. This will be our interface into persistence across our PHP applications for the foreseeable future. We will continue to use our active record implementation underneath DAL until we decide to remove it completely, at which point DAL will stay put.

The main interface of DAL mimics the API of Doctrine ORM, with similarly named `getRepository()`, `persist()` and `flush()` methods. The repositories exposed through the `getRepository()` method even implement Doctrine's `ObjectRepository`, all with the aim of having a common ground with one of the most feature-complete data mapper libraries for PHP.

It can be installed in whichever way you prefer, but we recommend [Composer](https://packagist.org/packages/graze/dal).

```
{
    "require": {
        "graze/dal": "^1.0"
    }
}
```

```
$ composer require graze/dal
```

Documentation
-------------

[](#documentation)

- [Getting started with Eloquent](#getting-started-with-eloquent)
- [Getting started with Doctrine](#getting-started-with-doctrine)
- [Getting started with PDO](#getting-started-with-pdo)
- [Relationships](#relationships)
    - [Many to many relationships](#many-to-many-relationships)
- [Using Multiple Adapters](#using-multiple-adapters)
- [Database Support](#database-support)

Getting started with Eloquent
-----------------------------

[](#getting-started-with-eloquent)

Using Eloquent with DAL requires the `illuminate/eloquent` package. You may also find the following resources helpful if you're using Eloquent outside of Laravel: [How to use Eloquent outside of Laravel](https://laracasts.com/lessons/how-to-use-eloquent-outside-of-laravel), [Using Eloquent outside Laravel](https://vkbansal.me/blog/using-eloquent-outside-laravel/).

#### Setting up the DalManager

[](#setting-up-the-dalmanager)

```
use Graze\Dal\Adapter\Orm\EloquentOrmAdapter;

$eloquentAdapter = EloquentOrmAdapter::createFromYaml(/*Eloquent DB Connection*/, ['path/to/config/eloquent.yml']);
$dal = new DalManager([$eloquentAdapter]);
```

We've got a `DalManager` object setup in our application, now we need to write some configuration for our entities:

#### Writing the config

[](#writing-the-config)

Adapters come with two methods of configuration `createFromYaml` and `createFromArray`, in this documentation all examples are in YAML, but you can just use an array or anything that can convert into an array.

```
App\Entity\Product:
    record: App\Eloquent\Product
    adapter: Graze\Dal\Adapter\Orm\EloquentOrmAdapter
    repository: App\Repository\ProductRepository
    table: products
    fields:
        id:
            mapsTo: id
            type: int
        name:
            mapsTo: name
            type: string
```

This is the config for a basic `Product` entity in our application. It's configured with the following fields:

- `record` - This is the class provided by your persistence layer, in this case an Eloquent model.
- `adapter` - This is the adapter this entity will be managed by.
- `repository` (optional) - This is the custom repository class for this entity, DAL provides a generic repository if you don't specify one here.
- `table` - This field is specific to the adapter, in this case we need to provide our Eloquent model with the table name for this entity.
- `fields` - Defines each field on the entity, the `mapsTo` field refers to the property on the underlying Eloquent model that we're going to use for this field.

#### Generating the classes

[](#generating-the-classes)

With this setup, we don't actually need to write any PHP code for our entity, DAL can generate it all for us. By running this command, DAL will generate an entity class, a repository and the underlying Eloquent model we need to get started.

```
$ bin/dal generate path/to/config/eloquent.yml App src
```

#### Using the DalManager

[](#using-the-dalmanager)

We've now got everything we need to start using our entity, which is done like so:

```
$product = $dalManager->getRepository('App\Entity\Product')->find(1);
echo $product->getName();
```

Getting started with Doctrine
-----------------------------

[](#getting-started-with-doctrine)

Getting started with Doctrine is very similar to Eloquent. The key differences are that DAL does not currently support generating the underlying Doctrine classes and configurationg for you, so you will need to write that yourself. You will also need the `doctrine/orm` package.

#### Setting up the DalManager

[](#setting-up-the-dalmanager-1)

```
use Graze\Dal\Adapter\Orm\DoctrineOrmAdapter;
use Doctrine\ORM\EntityManager;

$em = new EntityManager(); // see Doctrine's documentation for setting this up
$doctrineAdapter = DoctrineOrmAdapter::createFromYaml($em, ['path/to/config/doctrine.yml']);
$dal = new DalManager([$doctrineAdapter]);
```

#### Writing the config

[](#writing-the-config-1)

```
App\Entity\Product:
    record: App\Doctrine\Product
    repository: App\Repository\ProductRepository
    fields:
        id:
            mapsTo: id
            type: int
        name:
            mapsTo: name
            type: string
```

You will also need to write the Doctrine config for the underlying Doctrine entity.

#### Generating the DAL entities and repositories

[](#generating-the-dal-entities-and-repositories)

```
$ bin/dal generate path/to/config/doctrine.yml App src
```

**Note:** Generating Doctrine entities is currently **not supported**. You will have to write those yourself.

#### Using the DalManager

[](#using-the-dalmanager-1)

```
$product = $dalManager->getRepository('App\Entity\Product')->find(1);
echo $product->getName();
```

Getting started with PDO
------------------------

[](#getting-started-with-pdo)

DAL also has a very plain `PdoAdapter` if you don't need the features that ORMs come with but you still want a sensible set of interfaces for managing your data. This does rely on the `aura/sql` package though, so make sure you have that configured as a dependency of your app.

#### Setting up the DalManager

[](#setting-up-the-dalmanager-2)

```
use Graze\Dal\Adapter\Pdo\PdoAdapter;
use Aura\Sql\ExtendedPdo;

$pdo = new ExtendedPdo(); // @see https://github.com/auraphp/Aura.Sql#lazy-connection-instance for setting this up
$pdoAdapter = PdoAdapter::createFromYaml($pdo, ['path/to/config/pdo.yml']);
$dal = new DalManager([$pdoAdapter]);
```

#### Writing the config

[](#writing-the-config-2)

```
App\Entity\Product:
    table: products
    repository: App\Repository\ProductRepository
    fields:
        id:
            mapsTo: id
            type: int
        name:
            mapsTo: name
            type: string
```

Notice that there's no `record` field here, as there is no underlying model or record class with PDO this is unnecessary.

#### Generating the DAL entities and repositories

[](#generating-the-dal-entities-and-repositories-1)

There's no records/models to generate, so we just need to generate the DAL entities and repositories by running:

```
$ bin/dal generate path/to/config/pdo.yml App src
```

#### Using the DalManager

[](#using-the-dalmanager-2)

```
$product = $dalManager->getRepository('App\Entity\Product')->find(1);
echo $product->getName();
```

Relationships
-------------

[](#relationships)

Relationships between entities should be defined at the DAL level and not in the underlying persistence layers. This is to facilitate entities being managed by different adapters.

```
App\Entity\Customer:
    record: App\Eloquent\Customer
    repository: App\Repository\CustomerRepository
    table: customers
    fields:
        id:
            mapsTo: id
            type: int
        firstName:
            mapsTo: first_name
            type: string
        lastName:
            mapsTo: last_name
            type: string
    related:
        orders:
            type: oneToMany
            entity: App\Entity\Order
            foreignKey: customer_id
            collection: true

App\Entity\Order:
    record: App\Eloquent\Order
    table: orders
    fields:
        id:
            mapsTo: id
            type: int
        price:
            mapsTo: price
            type: float
    related:
        customer:
            type: manyToOne
            entity: App\Entity\Customer
            localKey: customer_id
```

This example shows a simple relationship between a Customer and an Order. The Customer owns many Orders and so has a `oneToMany`type with the Order entity, using the `customer_id` field on the orders table as a foreign key and we denote that this will be a collection of entities.

On the Order entity configuration, we have a single Customer field defined as `manyToOne` as an Order belongs to a Customer and this uses the `customer_id` field on the orders table as the local key for determining which Customer owns this Order.

The `localKey` and `foreignKey` refer to fields on the database tables themselves, not the DAL entities or underlying persistence layer entities. For this reason, relationships are currently only supported where on at least one side of the relationship there is an entity using SQL as its underlying storage mechanism.

The example above shows the `manyToOne` and `oneToMany` relationship types, there is also `manyToMany`.

#### Many to many relationships

[](#many-to-many-relationships)

Many to many relationships require two entities and a pivot table that stores the relationship between them:

```
App\Entity\Order:
    record: App\Eloquent\Order
    table: orders
    fields:
        id:
            mapsTo: id
            type: int
        price:
            mapsTo: price
            type: float
    related:
        customer:
            type: manyToOne
            entity: App\Entity\Customer
            localKey: customer_id
        products:
            type: manyToMany
            entity: App\Entity\Product
            pivot: order_item
            localKey: order_id
            foreignKey: product_id
            collection: true
```

Here we have extended our Order entity to relate to many Products and of course, a single Product can also belong to many Orders.

As with other relationships we define the `type` and the `entity`, then we need to define the `pivot` table and the two keys, `localKey` and `foreignKey` that are on the pivot table. The `localKey` being the field storing the ID for the entity this configuration is for, in this case Order, and the `foreignKey` being the field storing the ID for the entity that we're relating to, in this case Product.

```
$ bin/dal generate path/to/config/eloquent.yml App src
```

```
$customer = $dalManager->getRepository('App\Entity\Customer')->findBy(['email' => 'customer@example.com']);
$orders = $customer->getOrders();

foreach ($orders as $order) {
    echo $order->getPrice();
}
```

Using Multiple Adapters
-----------------------

[](#using-multiple-adapters)

```
use Graze\Dal\Adapter\Pdo\PdoAdapter;
use Graze\Dal\Adapter\Orm\EloquentOrmAdapter;
use Aura\Sql\ExtendedPdo;

$pdoAdapter = PdoAdapter::createFromYaml(new ExtendedPdo(/*see Aura docs*/), ['path/to/config/pdo.yml']);
$eloquentAdapter = EloquentOrmAdapter::createFromYaml(/* see eloquent docs */, ['path/to/config/eloquent.yml']);
$dalManager = new DalManager([$pdoAdapter, $eloquentAdapter]);
```

Now that we've got a DalManager setup with two configured adapters, we can write config to setup two entities with different adapters and create relationships between them:

```
# eloquent.yml
App\Entity\Customer:
    record: App\Eloquent\Customer
    repository: App\Repository\CustomerRepository
    table: customers
    fields:
        id:
            mapsTo: id
            type: int
        firstName:
            mapsTo: first_name
            type: string
        lastName:
            mapsTo: last_name
            type: string
    related:
        orders:
            type: oneToMany
            entity: App\Entity\Order
            foreignKey: customer_id
            collection: true

# pdo.yml
App\Entity\Order:
    table: orders
    fields:
        id:
            mapsTo: id
            type: int
        price:
            mapsTo: price
            type: float
    related:
        customer:
            type: manyToOne
            entity: App\Entity\Customer
            localKey: customer_id
```

Now we can generate all the entities, repositories and records we need:

```
$ bin/dal generate path/to/config/eloquent.yml App src
```

And use just like we have in all the previous examples:

```
$customer = $dalManager->getRepository('App\Entity\Customer')->findBy(['email' => 'customer@example.com']);
$orders = $customer->getOrders();

foreach ($orders as $order) {
    echo $order->getPrice();
}
```

This allows us to have different data handled by different adapters and storage mechanisms but create relationships between them through a single interface. How each entity is managed behind the scenes is abstracted away from our high-level code.

This opens up possibilities such as:

```
use Graze\Dal\Adapter\Orm\EloquentOrmAdapter;
use App\Dal\Adapter\HttpAdapter;

$httpAdapter = HttpAdapter::createFromYaml(new GuzzleHttp\Client(), ['path/to/config/http.yml']);
$eloquentAdapter = EloquentOrmAdapter::createFromYaml(/* see eloquent docs */, ['path/to/config/eloquent.yml']);
$dalManager = new DalManager([$httpAdapter, $eloquentAdapter]);
```

Database Support
----------------

[](#database-support)

In theory, DAL supports any database that is supported by the underlying persistence layers, Doctrine, Eloquent etc. However DAL only officially supports MySQL. This is because the code that handles the relationship types does currently rely on SQL queries written within DAL which have only been tested on MySQL.

If you're working with a database that is supported by your persistence layer, do give it a go, in 90% of cases it will probably work great. We will work to officially support other databases in the future.

Contributing &amp; Support
--------------------------

[](#contributing--support)

If you have a support query, please open an issue and label it as 'support'. If you'd like to contribute, please open a PR or an issue to discuss it first. Documentation contributions are incredibly welcome.

#### Development

[](#development)

There's a docker-compose file that you can use to spin up an environment for development and testing:

```
$ make install
$ make test
```

License
-------

[](#license)

The content of this library is released under the **MIT License** by **Nature Delivered Ltd**.
 You can find a copy of this license in [`LICENSE`](/LICENSE) or at .

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance15

Infrequent updates — may be unmaintained

Popularity30

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 63.6% 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 ~57 days

Recently: every ~102 days

Total

12

Last Release

3341d ago

Major Versions

v0.1.1 → v1.0.0-alpha22015-07-27

PHP version history (2 changes)v0.1PHP &gt;=5.4.0

v1.0.0-alpha3PHP &gt;=5.5.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/637788?v=4)[graze.com](/maintainers/graze)[@graze](https://github.com/graze)

---

Top Contributors

[![wpillar](https://avatars.githubusercontent.com/u/188514?v=4)](https://github.com/wpillar "wpillar (77 commits)")[![adlawson](https://avatars.githubusercontent.com/u/200351?v=4)](https://github.com/adlawson "adlawson (30 commits)")[![joemeehan](https://avatars.githubusercontent.com/u/2518301?v=4)](https://github.com/joemeehan "joemeehan (5 commits)")[![john-n-smith](https://avatars.githubusercontent.com/u/1314694?v=4)](https://github.com/john-n-smith "john-n-smith (4 commits)")[![sjparkinson](https://avatars.githubusercontent.com/u/51677?v=4)](https://github.com/sjparkinson "sjparkinson (2 commits)")[![biggianteye](https://avatars.githubusercontent.com/u/1482649?v=4)](https://github.com/biggianteye "biggianteye (2 commits)")[![eddread](https://avatars.githubusercontent.com/u/637793?v=4)](https://github.com/eddread "eddread (1 commits)")

---

Tags

data-access-layerphpabstractiondatadatabaseormdbalaccessdbmapperrecordConnectionactive-recorddata mapperactiverecorddatamappergrazePersistdaodalpersistance

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/graze-dal/health.svg)

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

###  Alternatives

[vlucas/spot2

Simple DataMapper built on top of Doctrine DBAL

605392.8k7](/packages/vlucas-spot2)[kassko/data-mapper

A mapper which gives a lot of features to representate some raw data like objects

1338.5k1](/packages/kassko-data-mapper)[tommyknocker/pdo-database-class

Framework-agnostic PHP database library with unified API for MySQL, MariaDB, PostgreSQL, SQLite, MSSQL, and Oracle. Query Builder, caching, sharding, window functions, CTEs, JSON, migrations, ActiveRecord, CLI tools, AI-powered analysis. Zero external dependencies.

845.7k](/packages/tommyknocker-pdo-database-class)[wayofdev/laravel-cycle-orm-adapter

🔥 A Laravel adapter for CycleORM, providing seamless integration of the Cycle DataMapper ORM for advanced database handling and object mapping in PHP applications.

3516.7k3](/packages/wayofdev-laravel-cycle-orm-adapter)

PHPackages © 2026

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