Doctrine filters

Doctrine features a filter system that allows the developer to add SQL to the conditional clauses of queries, regardless the place where the SQL is generated. The filter functionality works on SQL level. Each time the system iterates over all the enabled filters, adding a new SQL part as a filter returns.

By adding SQL to the conditional clauses of queries, the filter system filters out rows belonging to the entities at the level of the SQL result set.

Creation of a Doctrine filter class:

namespace Acme\DemoBundle\Filter;
 
use Doctrine\ORM\Mapping\ClassMetaData,
    Doctrine\ORM\Query\Filter\SQLFilter;
 
class MyBlogFilter extends SQLFilter
{
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
    {
        // Check if the entity implements the Blog interface
        if (!$targetEntity->reflClass->implementsInterface('Blog')) {
            return "";
        }
 
        return $targetTableAlias.'.active = 1';
    }
}

Configure the Doctrine filter:

# Enable the filter in app/config/config.yml
doctrine:  
  orm:
    filters:
      blog_filter:
        class:   Acme\DemoBundle\Filter\MyBlogFilter
        enabled: true

Filters can be disabled and enabled via the FilterCollection which is stored in the EntityManager. The FilterCollection#enable($name) method will retrieve the filter object. You can set the filter parameters on that object.

<?php
$filter = $em->getFilters()->enable('blog_filter');
 
// Disable it
$filter = $em->getFilters()->disable('blog_filter');