PHPackages                             primasoftware/doctrine-specification - 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. primasoftware/doctrine-specification

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

primasoftware/doctrine-specification
====================================

Specification Pattern for your Doctrine repositories

1.0(3y ago)04.2k↓50%1MITPHPPHP &gt;=5.4

Since Jul 18Pushed 3y ago1 watchersCompare

[ Source](https://github.com/cdomigan/Doctrine-Specification)[ Packagist](https://packagist.org/packages/primasoftware/doctrine-specification)[ Docs](http://developer.happyr.com/)[ RSS](/packages/primasoftware-doctrine-specification/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (2)Versions (22)Used By (0)

Happyr Doctrine Specification
=============================

[](#happyr-doctrine-specification)

[![Build Status](https://camo.githubusercontent.com/c4e499f1371ab27aa36ebaffd52ebcc6fd7a6a9ee6a4fc61568858c258b599f8/68747470733a2f2f7472617669732d63692e6f72672f4861707079722f446f637472696e652d53706563696669636174696f6e2e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/Happyr/Doctrine-Specification)[![SensioLabsInsight](https://camo.githubusercontent.com/8ae7e63ed6ee295003793c8c84867f6f032e3325adad070868fdee89575da4e5/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f34346334323561662d393066362d346332352d623738392d3465636532386230316132622f6d696e692e706e67)](https://insight.sensiolabs.com/projects/44c425af-90f6-4c25-b789-4ece28b01a2b)[![Latest Stable Version](https://camo.githubusercontent.com/cee4a363395b239c8dde016a36ae212a9f74b06cebd0f5dd8b221e02ac5f36c9/68747470733a2f2f706f7365722e707567782e6f72672f6861707079722f646f637472696e652d73706563696669636174696f6e2f762f737461626c652e737667)](https://packagist.org/packages/happyr/doctrine-specification)[![Monthly Downloads](https://camo.githubusercontent.com/b0a3f692d7bf6cf474a98a7e2c64e12a30eac13994bf4a0bce0c5d21e86be72c/68747470733a2f2f706f7365722e707567782e6f72672f6861707079722f646f637472696e652d73706563696669636174696f6e2f642f6d6f6e74686c792e706e67)](https://packagist.org/packages/happyr/doctrine-specification)

This library gives you a new way for writing queries. Using the [Specification pattern](http://en.wikipedia.org/wiki/Specification_pattern) you will get small Specification classes that are highly reusable.

The problem with writing Doctrine queries is that it soon will be messy. When your application grows you will have 20+ function in your Doctrine repositories. All with long and complicated QueryBuilder calls. You will also find that you are using a lot of parameters to the same method to accommodate different use cases.

After a discussion with Kacper Gunia on [Sound of Symfony podcast](http://www.soundofsymfony.com/episode/episode-2/) about how to test your Doctrine repositories properly, we (Kacper and Tobias) decided to create this library. We have been inspired by Benjamin Eberlei's thoughts in his [blog post](http://www.whitewashing.de/2013/03/04/doctrine_repositories.html).

### Table of contents

[](#table-of-contents)

1. [Motivation](#why-do-we-need-this-lib) and [basic understanding](#the-practical-differences) (this page)
2. [Usage examples](docs/0-usage.md)
3. [Create your own spec](docs/1-creatingSpecs.md)
4. [Contributing to the library](CONTRIBUTING.md)

Why do we need this lib?
------------------------

[](#why-do-we-need-this-lib)

You are probably wondering why we created this library. Your entity repositories are working just fine as they are, right?

But if your friend open one of your repository classes he/she would probably find that the code is not as perfect as you thought. Entity repositories have a tendency to get messy. Problems may include:

- Too many functions (`findActiveUser`, `findActiveUserWithPicture`, `findUserToEmail`, etc)
- Some functions have too many arguments
- Code duplication
- Difficult to test

Requirements of the solution
----------------------------

[](#requirements-of-the-solution)

The solution should have the following features:

- Easy to test
- Easy to extend, store and run
- Re-usable code
- Single responsibility principle
- Hides the implementation details of the ORM. (This might seen like nitpicking, however it leads to bloated client code doing the query builder work over and over again.)

The practical differences
-------------------------

[](#the-practical-differences)

This is an example of how you use the lib. Say that you want to fetch some Adverts and close them. We should select all Adverts that have their `endDate` in the past. If `endDate` is null make it 4 weeks after the `startDate`.

```
// Not using the lib
$qb = $this->em->getRepository('HappyrRecruitmentBundle:Advert')
    ->createQueryBuilder('r');

return $qb->where('r.ended = 0')
    ->andWhere(
        $qb->expr()->orX(
            'r.endDate < :now',
            $qb->expr()->andX(
                'r.endDate IS NULL',
                'r.startDate < :timeLimit'
            )
        )
    )
    ->setParameter('now', new \DateTime())
    ->setParameter('timeLimit', new \DateTime('-4weeks'))
    ->getQuery()
    ->getResult();
```

```
// Using the lib
$spec = Spec::andX(
    Spec::eq('ended', 0),
    Spec::orX(
        Spec::lt('endDate', new \DateTime()),
        Spec::andX(
            Spec::isNull('endDate'),
            Spec::lt('startDate', new \DateTime('-4weeks'))
        )
    )
);

return $this->em->getRepository('HappyrRecruitmentBundle:Advert')->match($spec);
```

Yes, it looks pretty much the same. But the later is reusable. Say you want another query to fetch Adverts that we should close but only for a specific company.

#### Doctrine Specification

[](#doctrine-specification)

```
class AdvertsWeShouldClose extends BaseSpecification
{
    public function getSpec()
    {
        return Spec::andX(
            Spec::eq('ended', 0),
            Spec::orX(
                Spec::lt('endDate', new \DateTime()),
                Spec::andX(
                    Spec::isNull('endDate'),
                    Spec::lt('startDate', new \DateTime('-4weeks'))
                )
            )
        );
    }
}

class OwnedByCompany extends BaseSpecification
{
    private $companyId;

    public function __construct(Company $company, $dqlAlias = null)
    {
        parent::__construct($dqlAlias);
        $this->companyId = $company->getId();
    }

    public function getSpec()
    {
        return Spec::andX(
            Spec::join('company', 'c'),
            Spec::eq('id', $this->companyId, 'c')
        );
    }
}

class SomeService
{
    /**
     * Fetch Adverts that we should close but only for a specific company
     */
    public function myQuery(Company $company)
    {
        $spec = Spec::andX(
            new AdvertsWeShouldClose(),
            new OwnedByCompany($company)
        );

        return $this->em->getRepository('HappyrRecruitmentBundle:Advert')->match($spec);
    }
}
```

#### QueryBuilder

[](#querybuilder)

If you were about to do the same thing with only the QueryBuilder it would look like this:

```
class AdvertRepository extends EntityRepository
{
    protected function filterAdvertsWeShouldClose($qb)
    {
        return $qb
            ->andWhere('r.ended = 0')
            ->andWhere(
                $qb->expr()->orX(
                    'r.endDate < :now',
                    $qb->expr()->andX('r.endDate IS NULL', 'r.startDate < :timeLimit')
                )
            )
            ->setParameter('now', new \DateTime())
            ->setParameter('timeLimit', new \DateTime('-4weeks'))
        ;
    }

    protected function filterOwnedByCompany($qb, Company $company)
    {
        return $qb
            ->join('company', 'c')
            ->andWhere('c.id = :company_id')
            ->setParameter('company_id', $company->getId())
        ;
    }

    public function myQuery(Company $company)
    {
        $qb = $this->em->getRepository('HappyrRecruitmentBundle:Advert')->createQueryBuilder('r');
        $this->filterAdvertsWeShouldClose($qb)
        $this->filterOwnedByCompany($qb, $company)

        return $qb->getQuery()->getResult();
    }
}
```

The issues with the QueryBuilder implementation are:

- You may only use the filters `filterOwnedByCompany` and `filterAdvertsWeShouldClose` inside AdvertRepository.
- You can not build a tree with And/Or/Not. Say that you want every Advert but not those owned by $company. There is no way to reuse `filterOwnedByCompany()` in that case.
- Different parts of the QueryBuilder filtering cannot be composed together, because of the way the API is created. Assume we have a filterGroupsForApi() call, there is no way to combine it with another call filterGroupsForPermissions(). Instead reusing this code will lead to a third method filterGroupsForApiAndPermissions().

Continue reading
----------------

[](#continue-reading)

You may want to take a look at some [usage examples](docs/0-usage.md) or find out how to [create your own spec](docs/1-creatingSpecs.md).

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity21

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 80.1% 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 ~154 days

Recently: every ~512 days

Total

20

Last Release

1398d ago

Major Versions

0.13 → 1.02022-07-20

PHP version history (2 changes)0.1.0-alphaPHP &gt;=5.4

0.2.0PHP &gt;=5.3.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/8da90a5af2fe367d0efda917002b84c924476e8bf92185d96807cc831014a1db?d=identicon)[cdomigan](/maintainers/cdomigan)

---

Top Contributors

[![Nyholm](https://avatars.githubusercontent.com/u/1275206?v=4)](https://github.com/Nyholm "Nyholm (157 commits)")[![cordoval](https://avatars.githubusercontent.com/u/328359?v=4)](https://github.com/cordoval "cordoval (11 commits)")[![cakper](https://avatars.githubusercontent.com/u/1022346?v=4)](https://github.com/cakper "cakper (11 commits)")[![cdomigan](https://avatars.githubusercontent.com/u/711882?v=4)](https://github.com/cdomigan "cdomigan (5 commits)")[![adamquaile](https://avatars.githubusercontent.com/u/69929?v=4)](https://github.com/adamquaile "adamquaile (2 commits)")[![AP-Hunt](https://avatars.githubusercontent.com/u/1747386?v=4)](https://github.com/AP-Hunt "AP-Hunt (2 commits)")[![thundo](https://avatars.githubusercontent.com/u/703181?v=4)](https://github.com/thundo "thundo (2 commits)")[![timroberson](https://avatars.githubusercontent.com/u/913294?v=4)](https://github.com/timroberson "timroberson (2 commits)")[![Strontium-90](https://avatars.githubusercontent.com/u/1295249?v=4)](https://github.com/Strontium-90 "Strontium-90 (2 commits)")[![kgilden](https://avatars.githubusercontent.com/u/918599?v=4)](https://github.com/kgilden "kgilden (1 commits)")[![drewclauson](https://avatars.githubusercontent.com/u/10655807?v=4)](https://github.com/drewclauson "drewclauson (1 commits)")

---

Tags

specificationdoctrinerepository

### Embed Badge

![Health badge](/badges/primasoftware-doctrine-specification/health.svg)

```
[![Health](https://phpackages.com/badges/primasoftware-doctrine-specification/health.svg)](https://phpackages.com/packages/primasoftware-doctrine-specification)
```

###  Alternatives

[happyr/doctrine-specification

Specification Pattern for your Doctrine repositories

452915.0k8](/packages/happyr-doctrine-specification)[scienta/doctrine-json-functions

A set of extensions to Doctrine that add support for json query functions.

58723.9M36](/packages/scienta-doctrine-json-functions)[laravel-doctrine/orm

An integration library for Laravel and Doctrine ORM

8425.3M87](/packages/laravel-doctrine-orm)[kphoen/rulerz

Powerful implementation of the Specification pattern

8831.3M6](/packages/kphoen-rulerz)[damienharper/auditor-bundle

Integrate auditor library in your Symfony projects.

4542.8M](/packages/damienharper-auditor-bundle)[rikbruil/doctrine-specification

Doctrine Specification pattern for building queries dynamically and with re-usable classes for composition.

50251.6k2](/packages/rikbruil-doctrine-specification)

PHPackages © 2026

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