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

gedmo/doctrine-extensions

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Installation:

    composer require gedmo/doctrine-extensions
    

    Add to config/app.php under providers (if using Doctrine via Laravel Doctrine or similar):

    Gedmo\DoctrineExtensions\ServiceProvider::class,
    
  2. Enable in Doctrine: Configure in your Doctrine config (e.g., config/doctrine.php):

    'orm' => [
        'entity_managers' => [
            'default' => [
                'extensions' => [
                    'Gedmo\\DoctrineExtensions\\Timestampable\\TimestampableListener',
                    'Gedmo\\DoctrineExtensions\\SoftDeleteable\\SoftDeleteableListener',
                    // Add other listeners as needed
                ],
            ],
        ],
    ],
    
  3. First Use Case: Add a Timestampable entity to track creation/modification:

    use Gedmo\Mapping\Annotation as Gedmo;
    
    /**
     * @Gedmo\Timestampable(on="create")
     */
    class Post
    {
        /**
         * @var \DateTime
         * @Gedmo\Timestampable(on="create")
         */
        private $createdAt;
    
        /**
         * @var \DateTime
         * @Gedmo\Timestampable(on="update")
         */
        private $updatedAt;
    }
    

    Run migrations (php artisan doctrine:migrations:diff + php artisan doctrine:migrations:migrate).


Implementation Patterns

Common Workflows

  1. Timestampable:

    • Use @Gedmo\Timestampable on properties or class level.
    • Override setCreatedAt()/setUpdatedAt() if custom logic is needed.
    • Example: Auto-log audit trails with createdAt/updatedAt.
  2. SoftDeleteable:

    • Add deletedAt column (type: datetime, nullable).
    • Query with ->whereNull('deletedAt') or use SoftDeleteableQueryBuilder.
    • Force-delete with ->forceDelete().
  3. Slugable:

    • Configure via YAML/Annotation:
      Gedmo\Sluggable:
          fields: ['title']
          separator: '-'
      
    • Generate slugs on-the-fly or pre-save.
  4. Tree:

    • Define parent/child relationships with @Gedmo\TreeType.
    • Use getChildren(), getParent(), or getRoot() methods.
    • Rebuild tree structure with ->rebuildTree().
  5. Loggable:

    • Track changes via @Gedmo\Loggable.
    • Access logs with getLogEntries() or query via LogEntry entity.

Integration Tips

  • Events: Listen to prePersist, preUpdate, or postFlush to extend behavior (e.g., validate slugs before save).
  • QueryBuilder: Use ->where('deletedAt IS NULL') for soft-deleted models.
  • Custom Fields: Extend behaviors by implementing Gedmo\Mapping\LifecycleEventArgs interfaces.
  • MongoDB: Replace Timestampable with Gedmo\MongoDB\Timestampable\TimestampableListener for ODM.

Gotchas and Tips

Pitfalls

  1. Listener Registration:

    • Forgetting to register listeners in Doctrine config (e.g., extensions array).
    • Fix: Verify listeners are loaded in config/doctrine.php.
  2. Column Mismatches:

    • Adding @Gedmo\Timestampable to a non-datetime column.
    • Fix: Ensure column types match (e.g., datetime for createdAt).
  3. Tree Rebuilding:

    • Modifying tree structure without ->rebuildTree() can corrupt hierarchy.
    • Fix: Call rebuildTree() after bulk updates.
  4. Soft Deletes in Queries:

    • Forgetting to filter deletedAt in queries returns soft-deleted records.
    • Fix: Use ->whereNull('deletedAt') or SoftDeleteableQueryBuilder.
  5. Slug Conflicts:

    • Duplicate slugs if not handled (e.g., case sensitivity or separator collisions).
    • Fix: Implement onDuplicate logic in setSlug() or use a unique constraint.

Debugging

  • Listener Not Triggering:

    • Check Doctrine event manager with dump($entityManager->getEventManager()->getListeners()).
    • Ensure listeners are registered in the correct entity manager.
  • Timestamp Overrides:

    • If createdAt updates on save, override setCreatedAt() to throw an exception.
  • Tree Path Errors:

    • Use ->getPath() to debug hierarchy issues (e.g., circular references).

Extension Points

  1. Custom Events:

    • Extend Gedmo\Mapping\LifecycleEventArgs for custom behaviors (e.g., trigger actions on preUpdate).
  2. Field Mapping:

    • Override getSlugSource() in entities to dynamically set slug fields.
  3. MongoDB Adaptations:

    • Replace Doctrine listeners with ODM equivalents (e.g., Gedmo\MongoDB\Timestampable).
  4. Validation:

    • Add prePersist listeners to validate fields (e.g., slug length) before save.

Config Quirks

  • Timezones: Ensure createdAt/updatedAt use consistent timezones (configure in config/app.php).
  • MongoDB vs. ORM: Some behaviors (e.g., Tree) have separate ODM implementations.
  • Caching: Clear cache (php artisan cache:clear) after adding new listeners.
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