2017 © Pedro Peláez
 

library doctrine-specification

Specification Pattern for your Doctrine repositories

image

happyr/doctrine-specification

Specification Pattern for your Doctrine repositories

  • Tuesday, April 18, 2017
  • by Nyholm
  • Repository
  • 19 Watchers
  • 249 Stars
  • 76,769 Installations
  • PHP
  • 9 Dependents
  • 0 Suggesters
  • 30 Forks
  • 34 Open issues
  • 14 Versions
  • 10 % Grown

The README.md

Happyr Doctrine Specification

Build Status Travis (.org) Latest Stable Version Packagist Monthly Downloads Packagist Total Downloads Packagist Quality Score, (*1)

This library gives you a new way for writing queries. Using the Specification pattern you will get small Specification classes that are highly reusable., (*2)

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., (*3)

After a discussion with Kacper Gunia on Sound of Symfony podcast 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., (*4)

Table of contents

  1. Motivation and basic understanding (this page)
  2. Usage examples
  3. Create your own spec
  4. Contributing to the library

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?, (*5)

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:, (*6)

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

Requirements of the solution

The solution should have the following features:, (*7)

  • 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

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., (*8)

// 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., (*9)

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

If you were about to do the same thing with only the QueryBuilder it would look like this:, (*10)

class AdvertRepository extends EntityRepository
{
    protected function filterAdvertsWeShouldClose($qb)
    {
        $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)
    {
        $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:, (*11)

  • 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

You may want to take a look at some usage examples or find out how to create your own spec., (*12)

The Versions

18/04 2017

dev-master

9999999-dev http://developer.happyr.com/

Specification Pattern for your Doctrine repositories

  Sources   Download

MIT

The Requires

 

The Development Requires

by Kacper Gunia

repository doctrine specification

30/03 2017

0.7.2

0.7.2.0 http://developer.happyr.com/

Specification Pattern for your Doctrine repositories

  Sources   Download

MIT

The Requires

 

The Development Requires

by Kacper Gunia

repository doctrine specification

09/11 2015

0.7.1

0.7.1.0 http://developer.happyr.com/

Specification Pattern for your Doctrine repositories

  Sources   Download

MIT

The Requires

 

The Development Requires

by Kacper Gunia

repository doctrine specification

21/08 2015

0.7.0

0.7.0.0 http://developer.happyr.com/

Specification Pattern for your Doctrine repositories

  Sources   Download

MIT

The Requires

 

The Development Requires

by Kacper Gunia

repository doctrine specification

21/08 2015

0.6.2

0.6.2.0 http://developer.happyr.com/

Specification Pattern for your Doctrine repositories

  Sources   Download

MIT

The Requires

 

The Development Requires

by Kacper Gunia

repository doctrine specification

12/08 2015

0.6.1

0.6.1.0 http://developer.happyr.com/

Specification Pattern for your Doctrine repositories

  Sources   Download

MIT

The Requires

 

The Development Requires

by Kacper Gunia

repository doctrine specification

25/04 2015

0.6.0

0.6.0.0 http://developer.happyr.com/

Specification Pattern for your Doctrine repositories

  Sources   Download

MIT

The Requires

 

The Development Requires

by Kacper Gunia

repository doctrine specification

04/04 2015

0.5.0

0.5.0.0 http://developer.happyr.com/

Specification Pattern for your Doctrine repositories

  Sources   Download

MIT

The Requires

 

The Development Requires

by Kacper Gunia

repository doctrine specification

15/03 2015

0.4.0

0.4.0.0 http://developer.happyr.com/

Specification Pattern for your Doctrine repositories

  Sources   Download

MIT

The Requires

 

The Development Requires

by Kacper Gunia

repository doctrine specification

19/10 2014

0.3.1

0.3.1.0 http://developer.happyr.com/

Specification Pattern for your Doctrine repositories

  Sources   Download

MIT

The Requires

 

The Development Requires

by Kacper Gunia

repository doctrine specification

23/09 2014

0.3.0

0.3.0.0 http://developer.happyr.com/

Specification Pattern for your Doctrine repositories

  Sources   Download

MIT

The Requires

 

The Development Requires

by Kacper Gunia

repository doctrine specification

17/09 2014

dev-patch-1

dev-patch-1 http://developer.happyr.com/

Specification to your Doctrine repositories

  Sources   Download

MIT

The Requires

 

The Development Requires

by Kacper Gunia

repository doctrine specification

16/09 2014

0.2.0

0.2.0.0 http://developer.happyr.com/

Specification to your Doctrine repositories

  Sources   Download

MIT

The Requires

 

The Development Requires

by Kacper Gunia

repository doctrine specification

18/07 2014

0.1.0-alpha

0.1.0.0-alpha http://developer.happyr.com/

Specification to your Doctrine repositories

  Sources   Download

MIT

The Requires

 

repository doctrine specification