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 Audit Bundle Laravel Package

damienharper/doctrine-audit-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require damienharper/auditor-bundle
    

    Add to config/bundles.php (Symfony 5+):

    return [
        // ...
        DamienHarper\AuditorBundle\DamienHarperAuditorBundle::class => ['all' => true],
    ];
    
  2. Configure in config/packages/auditor.yaml

    damien_harper_auditor:
        connection: default  # Doctrine connection name
        logger: true         # Enable logging (optional)
        log_entry_class: App\Entity\AuditLogEntry  # Custom log entry class
    
  3. First Use Case: Enable Auditing on an Entity Annotate your entity with @Audited:

    use Gedmo\Mapping\Annotation as Gedmo;
    
    /**
     * @Gedmo\Loggable
     */
    class Product {}
    

    Run migrations to create the audit table (if using Doctrine migrations):

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    

Implementation Patterns

Workflow: Tracking Changes

  1. Enable Auditing for Entities Use @Gedmo\Loggable on any Doctrine entity to track all CRUD operations:

    /**
     * @Gedmo\Loggable
     */
    class User {}
    
  2. Customize Audit Logs Override the default log entry class (App\Entity\AuditLogEntry) to add custom fields:

    use Gedmo\Loggable\Entity\AuditEntry;
    
    class CustomAuditLogEntry extends AuditEntry
    {
        /**
         * @ORM\Column(type="string", nullable=true)
         */
        private $customField;
    }
    
  3. Querying Audit Data Use Doctrine queries to fetch audit logs:

    $auditLogs = $entityManager->getRepository(AuditLogEntry::class)
        ->findBy(['objectClass' => User::class]);
    
  4. Exclude Fields from Auditing Use @Gedmo\Loggable\Exclude to skip specific fields:

    /**
     * @Gedmo\Loggable\Exclude
     */
    private $password;
    
  5. Bulk Operations For mass updates, use Auditor::setFlushMode(Auditor::FLUSH_DISABLED) to disable auditing temporarily:

    $auditor = $entityManager->getExtension('gedmo_auditor');
    $auditor->setFlushMode(Auditor::FLUSH_DISABLED);
    
    // Bulk operations here...
    
    $auditor->setFlushMode(Auditor::FLUSH_ENABLED);
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Auditing adds database writes for every change. Disable for high-frequency operations (e.g., batch jobs) using FLUSH_DISABLED.
    • Monitor query performance with doctrine:query profiling.
  2. Circular References

    • Auditing may fail if entities have circular references. Use @Gedmo\Loggable\Exclude or lazy-loading (@ORM\LazyGroup).
  3. Migration Conflicts

    • Audit tables are auto-generated. Manually editing them can break the bundle. Use migrations or doctrine:schema:update --force.
  4. Symfony Cache Issues

    • Clear cache after enabling auditing:
      php bin/console cache:clear
      

Debugging

  • Enable Logging Set logger: true in auditor.yaml to debug audit events in var/log/dev.log.

  • Check Audit Events Use the AuditorListener to log events manually:

    $event = $event->getObject();
    $this->logger->info('Audited entity: ' . get_class($event));
    

Extension Points

  1. Custom Audit Strategies Implement Gedmo\Loggable\LogEntry\AbstractLogEntry to create custom log entry classes.

  2. Event Subscribers Extend auditing logic via Symfony events:

    use Gedmo\Loggable\LoggableListener;
    
    class CustomAuditorSubscriber implements EventSubscriber
    {
        public function getSubscribedEvents()
        {
            return [
                LoggableListener::PRE_FLUSH_EVENT => 'onPreFlush',
            ];
        }
    }
    
  3. Filtering Audit Logs Use DQL to filter logs by date, user, or entity:

    $qb = $entityManager->createQueryBuilder();
    $qb->select('e')
       ->from(AuditLogEntry::class, 'e')
       ->where('e.timestamp > :date')
       ->setParameter('date', new \DateTime('-7 days'));
    
  4. Asynchronous Auditing Offload auditing to a queue (e.g., Symfony Messenger) for high-traffic apps:

    # config/packages/messenger.yaml
    framework:
        messenger:
            transports:
                async_audit: '%env(MESSENGER_TRANSPORT_DSN)%'
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware