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

Doctrine Extensions Bundle Laravel Package

chamber-orchestra/doctrine-extensions-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle Add to your project via Composer:

    composer require chamber-orchestra/doctrine-extensions-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        ChamberOrchestra\DoctrineExtensionsBundle\ChamberOrchestraDoctrineExtensionsBundle::class => ['all' => true],
    ];
    
  2. Register Doctrine Extensions Add the following to your config/packages/doctrine.yaml:

    doctrine:
        orm:
            dql:
                string_functions:
                    RANDOM: ChamberOrchestra\DoctrineExtensionsBundle\DQL\RandomFunction
            mappings:
                App:
                    is_bundle: false
                    type: attribute
                    dir: "%kernel.project_dir%/src/Entity"
                    prefix: "App\Entity"
                    alias: App
    
  3. First Use Case: Soft Deletes Apply the SoftDeletable trait to an entity:

    use ChamberOrchestra\DoctrineExtensionsBundle\Model\SoftDeletableTrait;
    
    #[ORM\Entity(repositoryClass: ChamberOrchestra\DoctrineExtensionsBundle\Repository\SoftDeletableRepository::class)]
    class Post
    {
        use SoftDeletableTrait;
    
        // ...
    }
    

    Enable the soft-delete filter in config/packages/doctrine.yaml:

    doctrine:
        orm:
            filters:
                softdeleteable:
                    class: ChamberOrchestra\DoctrineExtensionsBundle\Filter\SoftDeleteFilter
                    enabled: true
    

Implementation Patterns

Entity Traits

  • SoftDeletableTrait: Automatically adds deletedAt column and methods (isDeleted(), delete(), restore()).
    #[ORM\Entity(repositoryClass: SoftDeletableRepository::class)]
    class User
    {
        use SoftDeletableTrait;
    }
    
  • DecimalTrait: Handles PostgreSQL decimal fields with precision/scale.
    use ChamberOrchestra\DoctrineExtensionsBundle\Model\DecimalTrait;
    
    class Product
    {
        use DecimalTrait;
    
        #[ORM\Column(type: 'decimal', precision: 10, scale: 2)]
        private $price;
    }
    

Repository Base Classes

Extend SoftDeletableRepository for soft-delete-aware queries:

use ChamberOrchestra\DoctrineExtensionsBundle\Repository\SoftDeletableRepository;

class PostRepository extends SoftDeletableRepository
{
    public function findPublished(): array
    {
        return $this->createQueryBuilder('p')
            ->andWhere('p.publishedAt <= :now')
            ->setParameter('now', new \DateTime())
            ->getQuery()
            ->getResult();
    }
}

DQL Functions

Use RANDOM() in queries for shuffling results:

$qb = $this->createQueryBuilder('u')
    ->addSelect('RANDOM() as random_sort')
    ->orderBy('random_sort');

Workflows

  1. Soft Deletes:

    • Delete: $post->delete(); $em->flush();
    • Restore: $post->restore(); $em->flush();
    • Query: $posts = $repo->findAll(); (automatically excludes soft-deleted).
  2. Decimal Handling:

    • Set precision/scale in @ORM\Column and use getDecimal()/setDecimal() methods.
  3. Randomization:

    • Use RANDOM() in ORDER BY for shuffling or SELECT RANDOM() as random_value for weighted logic.

Gotchas and Tips

Pitfalls

  1. Soft-Delete Filter Scope:

    • The filter applies to all queries unless explicitly disabled:
      $qb->disableSoftDeleteFilter();
      
    • Use findAll() or findBy() cautiously—soft-deleted records are excluded by default.
  2. Decimal Precision:

    • Doctrine may throw InvalidArgumentException if precision/scale exceed PostgreSQL limits (e.g., precision > 131072).
    • Validate precision/scale in entity constructors or setters.
  3. DQL Function Registration:

    • Forgetting to register RANDOM in doctrine.yaml causes Unknown DQL function 'RANDOM' errors.
    • Verify registration with:
      php bin/console debug:container chamber_orchestra.doctrine_extensions.dql.random_function
      
  4. Repository Inheritance:

    • Extend SoftDeletableRepository only if using soft deletes. Mixing traits/repos incorrectly may break query building.

Debugging

  • Soft-Delete Queries: Enable SQL logging to verify filters:

    doctrine:
        dbal:
            logging: true
            logging_format: '%%sql%%'
    

    Look for WHERE deletedAt IS NULL in generated SQL.

  • Decimal Issues: Check for Doctrine\DBAL\Exception\InvalidFieldNameException if column names conflict with trait methods (e.g., deletedAt vs. deleted_at).

Extension Points

  1. Custom Filters: Extend ChamberOrchestra\DoctrineExtensionsBundle\Filter\AbstractFilter to create reusable query filters.

  2. DQL Functions: Add new functions by implementing Doctrine\ORM\Query\AST\Functions\FunctionNode and registering them in the bundle’s Resources/config/services.yaml.

  3. Traits: Override trait methods (e.g., getDeletedAt()) to customize behavior, but document changes clearly.

Configuration Quirks

  • Test Environments: Disable soft-delete filters in tests to avoid unintended exclusions:
    $em->getFilters()->disable('softdeleteable');
    
  • PostgreSQL-Specific: The decimal type relies on PostgreSQL’s numeric type. MySQL users may need a custom DBAL type.
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager