Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Symfony Query Bundle Laravel Package

derafu/symfony-query-bundle

Symfony bundle that integrates derafu/query into Symfony applications. Provides easy service wiring and configuration to use query objects/patterns in your project. See derafu docs for setup, usage, and available options.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require derafu/symfony-query-bundle
    

    Add the bundle to config/bundles.php:

    return [
        // ...
        Derafu\SymfonyQueryBundle\DerafuSymfonyQueryBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console config:dump-reference DerafuSymfonyQueryBundle
    

    Override in config/packages/derafu_symfony_query.yaml:

    derafu_symfony_query:
        default_locale: 'en'
        query_builder: '@derafu.query_builder'
    
  3. First Use Case Inject the query builder into a service/controller:

    use Derafu\Query\QueryBuilder;
    
    class ProductController extends AbstractController
    {
        public function __construct(
            private QueryBuilder $queryBuilder
        ) {}
    
        public function listProducts(): Response
        {
            $query = $this->queryBuilder->create()
                ->from(Product::class)
                ->select(['id', 'name', 'price']);
    
            $results = $query->getQuery()->getResult();
            // Render results...
        }
    }
    

Implementation Patterns

Core Workflows

  1. Dynamic Query Building Chain methods for flexible queries:

    $query = $this->queryBuilder->create()
        ->from('App\Entity\Product')
        ->where('price > :price', ['price' => 100])
        ->orderBy('name', 'ASC')
        ->limit(10);
    
  2. Integration with Doctrine Use the built-in Doctrine adapter:

    derafu_symfony_query:
        adapters:
            doctrine: true
    

    Then leverage Doctrine’s DQL in queries:

    $query->dql("SELECT p FROM App\Entity\Product p WHERE p.category = :cat")
        ->setParameter('cat', $category);
    
  3. Pagination

    $query->paginate(1, 20); // Page 1, 20 items/page
    $results = $query->getQuery()->getResult();
    $total = $query->getQuery()->getSingleScalarResult('SELECT COUNT(p.id) FROM App\Entity\Product p');
    
  4. Multi-Entity Joins

    $query->from(['p' => Product::class])
        ->join('p.category', 'c')
        ->select(['p.id', 'c.name as category']);
    

Symfony-Specific Patterns

  1. Dependency Injection Tag services for query building:

    services:
        App\Service\CustomQueryBuilder:
            tags: ['derafu.query_builder']
    
  2. Event Listeners Extend query behavior via events:

    use Derafu\Query\Event\QueryEvent;
    
    public function onQueryBuild(QueryEvent $event) {
        $query = $event->getQuery();
        $query->addWhere('active = 1');
    }
    

    Register in services.yaml:

    App\EventListener\QueryListener:
        tags:
            - { name: kernel.event_listener, event: derafu.query.build, method: onQueryBuild }
    
  3. API Platform Integration Use with API Platform filters:

    use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\AbstractFilter;
    
    class CustomFilter extends AbstractFilter {
        public function __construct(private QueryBuilder $queryBuilder) {}
    
        protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, ApiFilter $filter, array $context = []): void {
            $queryBuilder->addWhere($property . ' = :val', ['val' => $value]);
        }
    }
    

Gotchas and Tips

Common Pitfalls

  1. Locale Mismatch

    • Ensure default_locale in config matches your app’s locale. Queries may fail silently if locales differ.
    • Debug: Check Derafu\Query\Exception\LocaleException.
  2. Circular References in Joins

    • Avoid infinite loops in self-referential joins (e.g., Product->Category->Product). Use ->join()->where() instead of direct associations.
  3. Parameter Binding

    • Always use named parameters (:param) for security. Raw values may lead to SQL injection:
      // ❌ Vulnerable
      $query->where("price > $userInput");
      
      // ✅ Safe
      $query->where("price > :price", ['price' => $userInput]);
      
  4. Doctrine Adapter Quirks

    • If using Doctrine, ensure your entities have proper id fields. The bundle assumes primary keys are named id.
    • For custom primary keys, configure the adapter:
      derafu_symfony_query:
          adapters:
              doctrine:
                  primary_key: 'uuid'
      

Debugging Tips

  1. Query Logging Enable SQL logging in config/packages/dev/doctrine.yaml:

    doctrine:
        dbal:
            logging: true
            profiling: true
    

    Then inspect queries via Symfony’s profiler or var_dump($query->getQuery()->getSQL()).

  2. Event Debugging Dump query events in a listener:

    public function onQueryBuild(QueryEvent $event) {
        \dump($event->getQuery()->getSQL());
    }
    
  3. Performance

    • Use ->select() explicitly to avoid SELECT * queries.
    • For large datasets, add ->indexBy() to reduce memory usage:
      $query->indexBy('p.id');
      

Extension Points

  1. Custom Adapters Implement Derafu\Query\Adapter\AdapterInterface for non-Doctrine databases (e.g., MongoDB):

    class MongoAdapter implements AdapterInterface {
        public function createQueryBuilder(): QueryBuilder {
            return new QueryBuilder($this);
        }
        // ...
    }
    

    Register in config:

    derafu_symfony_query:
        adapters:
            mongo: App\Adapter\MongoAdapter
    
  2. Query Macros Define reusable query snippets in a service:

    class QueryMacros {
        public function activeProducts(QueryBuilder $qb): QueryBuilder {
            return $qb->addWhere('active = 1');
        }
    }
    

    Use via dependency injection.

  3. Validation Extend query validation with custom rules:

    use Derafu\Query\Validator\Constraint\QueryConstraint;
    
    #[QueryConstraint(maxDepth: 5)]
    class ProductQuery {}
    

Configuration Quirks

  • Caching: Enable query caching for repeated queries:
    derafu_symfony_query:
        cache:
            enabled: true
            provider: 'cache.app'
    
  • Strict Mode: Enable to catch potential issues early:
    derafu_symfony_query:
        strict_mode: true
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky