title: Implement specification pattern
body: <p>Attempting to use the specification pattern and have run into the issue of having it work in different implementations (e.g., in memory, orm, etc.). My main ORM is Doctrine, which means that my first choice was to have the specifications use Criterias as they work on ArrayCollections (for InMemory implementations) and on the ORM. Unfortunately they are fairly limited in the sorts of queries they can run (can't perform a join). </p>
  
  <p>As an example let's say I have a UserHasBoughtProduct specification that is given a product id in the constructor. The specification is very simple to write at a naive level. </p>
  
  <pre><code>public function isSpecifiedBy(User $user)
  {
      foreach ($user-&gt;getProducts() as $product)
      {
          if ($product-&gt;getId() == $this-&gt;productId)
          {
              return true;
          }
      }
  
      return false;
  }
  </code></pre>
  
  <p>However, what if I wanted to find all users that had bought the product? I would need to pass this specification to my UserRepository via some sort of findSpecifiedBy(Specification $specification); method. But this doesn't work in production as it would have to check every single user in the database. </p>
  
  <p>My next idea from here was that the specification be only an interface and the implementation was handled by the infrastructure. So, in my persistence\doctrine\user\ directory, I might have a UserHasBoughtProduct specification and in my persistence\InMemory\user directory I have another. This works, in a way, but is very annoying to have to use in code as I will need all of my specifications to be available either by a DI container or in some sort of factory. Not to mention that if I have a class which requires several specifications I would need to inject them all via the constructor. Smells bad.</p>
  
  <p>It would be much more preferable if I could simply do the following in a method:</p>
  
  <pre><code>$spec = new UserHasBoughtProductSpecification($productId);
  $users = $this-&gt;userRepository-&gt;findSatisfiedBy($spec);
  //or
  if ($spec-&gt;isSatisfiedby($user))
  {
  //do something
  }
  </code></pre>
  
  <p>Has anyone had experience doing this in PHP? How did you manage to implement specification pattern in such a way that it works in the real world and is usable in different backends such as InMemory, ORM, pure SQL, or anything else?</p>