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

Dc Event Bundle Laravel Package

andreas-glaser/dc-event-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require andreas-glaser/dc-event-bundle ^1
    

    Ensure your project uses Symfony 3.4+ and PHP 7.2+.

  2. Enable the Bundle: Add to config/bundles.php:

    return [
        // ...
        AndreasGlaser\DCEventBundle\DCEventBundle::class => ['all' => true],
    ];
    
  3. First Use Case:

    • Annotate an entity with @DCEntityEventHandler to attach a custom event handler.
    • Example: Track changes to an Article entity before/after persistence.

Where to Look First

  • Entity Annotations: Check src/Entity/ for entities needing lifecycle hooks.
  • Event Handlers: Look for EEH (Entity Event Handler) classes in src/EEH/ or create a new directory.
  • Doctrine Events: Review prePersist, postPersist, preUpdate, etc., in your handler classes.

Implementation Patterns

Common Workflows

  1. Change Tracking: Use ChangeSetHelper in preUpdate to inspect field changes:

    public function preUpdate(ChangeSetHelper $changeSet) {
        if ($changeSet->isChanged('subject')) {
            $this->entity->setSubject(strtoupper($changeSet->getOldValue('subject')));
        }
    }
    
  2. Conditional Logic: Implement prePersist to validate or transform data before saving:

    public function prePersist() {
        if (empty($this->entity->getBody())) {
            throw new \RuntimeException('Article body cannot be empty.');
        }
    }
    
  3. Post-Save Actions: Use postPersist or postUpdate to trigger side effects (e.g., logging, notifications):

    public function postPersist() {
        $this->logAction('article_created', $this->entity->getId());
    }
    
  4. Bulk Operations: Handle multiple flushes by clearing state in postUpdate/postRemove:

    public function postUpdate() {
        $this->entity = null; // Reset entity reference
    }
    

Integration Tips

  • Dependency Injection: Inject services into handlers via constructor (extend DCEntityEventHandlerBase):

    public function __construct(private LoggerInterface $logger) {}
    
  • Testing: Mock ChangeSetHelper in unit tests to verify logic:

    $changeSet = $this->createMock(ChangeSetHelper::class);
    $changeSet->method('isChanged')->willReturn(true);
    $handler->preUpdate($changeSet);
    
  • Performance: Avoid heavy operations in preFlush (e.g., API calls). Use async tasks for post-save actions.


Gotchas and Tips

Pitfalls

  1. Multiple Flushes:

    • Issue: Handlers may misbehave if EntityManager::flush() is called repeatedly (e.g., in loops).
    • Fix: Reset entity references in postUpdate/postRemove or use EntityManager::clear().
  2. ChangeSet Staleness:

    • Issue: ChangeSetHelper reflects state before the current operation. Use getOldValue()/getNewValue() carefully.
    • Tip: Log changesets for debugging:
      public function preUpdate(ChangeSetHelper $changeSet) {
          error_log($changeSet->getChanges());
      }
      
  3. Annotation Caching:

    • Issue: Symfony cache may not reflect @DCEntityEventHandler changes immediately.
    • Fix: Clear cache after adding/removing annotations:
      php bin/console cache:clear
      
  4. Circular Dependencies:

    • Issue: Handlers modifying related entities may cause infinite loops.
    • Tip: Use EntityManager::getUnitOfWork()->propertyChanged() to check if an entity is already being processed.

Debugging

  • Enable Doctrine Events: Add to config/packages/dev/doctrine.yaml:

    doctrine:
        orm:
            event_listeners:
                logger:
                    class: Doctrine\ORM\Debug\Logger\ORMLogger
                    tag: ['doctrine.event_listener']
    
  • Log Handlers: Override DCEntityEventHandlerBase to log lifecycle calls:

    public function __construct() {
        parent::__construct();
        $this->logger = new \Monolog\Logger('dc_event');
    }
    

Extension Points

  1. Custom Annotations: Extend the annotation system to support additional metadata (e.g., @DCEntityEventHandler(priority=10)).

  2. Global Handlers: Register handlers dynamically via services (e.g., for entities without annotations):

    services:
        App\EEH\GlobalArticleEEH:
            tags:
                - { name: 'dc_event.handler', entity: 'App\Entity\Article' }
    
  3. Async Processing: Offload post-save tasks to a queue (e.g., Symfony Messenger) in postPersist:

    public function postPersist() {
        $this->messageBus->dispatch(new NotifyArticleCreated($this->entity));
    }
    

Config Quirks

  • Bundle Priority: The bundle hooks into preFlush, which runs before prePersist/preUpdate. Ensure your logic accounts for this order.

  • Entity Manager Scope: Handlers are tied to the EntityManager instance. For multi-EM setups, register handlers per manager.

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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
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