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

c33s/doctrine-extra

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require c33s/doctrine-extra
    

    Ensure doctrine/orm is also installed (required dependency).

  2. First Use Case Extend a Doctrine entity with a trait from c33s/doctrine-extra. For example, use Timestampable for automatic timestamp management:

    use Doctrine\ORM\Mapping as ORM;
    use C33S\DoctrineExtra\Traits\Timestampable;
    
    #[ORM\Entity]
    class Post
    {
        use Timestampable;
    
        #[ORM\Id, ORM\GeneratedValue, ORM\Column]
        private ?int $id = null;
    }
    
    • Key Files to Review:
      • src/Traits/ for available traits.
      • src/DoctrineExtraBundle.php (if using Symfony) for bundle configuration.

Implementation Patterns

Common Workflows

  1. Timestamp Management Use Timestampable to auto-set createdAt and updatedAt fields:

    use C33S\DoctrineExtra\Traits\Timestampable;
    
    class Post
    {
        use Timestampable;
    
        #[ORM\Column(type: 'datetime')]
        private ?\DateTimeInterface $createdAt = null;
    
        #[ORM\Column(type: 'datetime')]
        private ?\DateTimeInterface $updatedAt = null;
    }
    
    • Workflow: Doctrine lifecycle events handle updates automatically.
  2. Sluggable Entities Use Sluggable to generate SEO-friendly slugs:

    use C33S\DoctrineExtra\Traits\Sluggable;
    
    class Post
    {
        use Sluggable;
    
        #[ORM\Column(length: 255, unique: true)]
        private ?string $slug = null;
    
        #[ORM\Column(length: 255)]
        private string $title;
    }
    
    • Configuration: Override getSlugSource() and getSlugOptions() in your entity.
  3. Soft Deletes Use SoftDeletable for soft-deletion logic:

    use C33S\DoctrineExtra\Traits\SoftDeletable;
    
    class Post
    {
        use SoftDeletable;
    
        #[ORM\Column(type: 'datetime', nullable: true)]
        private ?\DateTimeInterface $deletedAt = null;
    }
    
    • Query Filter: Add SoftDeleteableFilter to your EntityManager in Symfony or manually in Laravel.
  4. Blameable Entities Track entity creators/updaters with Blameable:

    use C33S\DoctrineExtra\Traits\Blameable;
    
    class Post
    {
        use Blameable;
    
        #[ORM\ManyToOne(targetEntity: User::class)]
        private ?User $createdBy = null;
    
        #[ORM\ManyToOne(targetEntity: User::class)]
        private ?User $updatedBy = null;
    }
    
    • Integration: Set setUserProvider() to inject the current user (e.g., from Symfony’s Security component).

Integration Tips

  • Laravel-Specific:

    • Use doctrine/orm via spatie/laravel-doctrine-orm for seamless integration.
    • Override getUser() in Blameable to fetch the authenticated user from Laravel’s Auth facade.
    • For soft deletes, extend Laravel’s SoftDeletes trait or use Doctrine’s SoftDeleteableFilter in queries.
  • Symfony-Specific:

    • Register the DoctrineExtraBundle in config/bundles.php.
    • Use dependency injection for user providers in Blameable.

Gotchas and Tips

Pitfalls

  1. Timestampable Defaults

    • If createdAt/updatedAt are not nullable, ensure they are initialized in the constructor or Doctrine will throw errors.
    • Fix: Add default values or use nullable: true in annotations.
  2. Sluggable Conflicts

    • Slug generation may fail if getSlugSource() returns null or empty values.
    • Fix: Validate source fields or provide a fallback in getSlugSource().
  3. Soft Deletes and Queries

    • Forgetting to add SoftDeleteableFilter to the EntityManager will bypass soft-delete logic.
    • Fix: In Symfony, enable the filter in doctrine.extra.listener.soft_deleteable service. In Laravel, manually apply the filter in repository methods:
      $query->andWhere('p.deletedAt IS NULL');
      
  4. Blameable User Provider

    • If getUser() returns null, createdBy/updatedBy will be null.
    • Fix: Implement a fallback (e.g., a default user) or throw an exception in getUser().
  5. Doctrine Lifecycle Events

    • Traits rely on Doctrine’s lifecycle events (e.g., prePersist, preUpdate). Ensure your entities are properly mapped and events are not overridden.

Debugging Tips

  • Enable Doctrine Logging:

    $entityManager->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
    

    Verify events are triggered (e.g., updatedAt updates).

  • Check Trait Methods: Use var_dump() or dd() in overridden methods (e.g., setSlugSource()) to debug slug generation.

  • Query Builder Issues: For soft deletes, inspect the generated SQL to confirm filters are applied:

    $query->getSQL(); // Check for `AND p.deleted_at IS NULL`
    

Extension Points

  1. Custom Traits Extend existing traits or create new ones by copying the pattern (e.g., Timestampable):

    trait CustomTrait
    {
        public function prePersist()
        {
            // Custom logic
        }
    }
    
  2. Override Trait Methods Customize behavior by overriding trait methods:

    class Post
    {
        use Sluggable;
    
        public function getSlugSource(): string
        {
            return $this->title . '-' . $this->id; // Custom slug logic
        }
    }
    
  3. Event Subscribers Use Doctrine’s event system to extend functionality:

    $eventManager->addEventSubscriber(new class implements EventSubscriber {
        public function getSubscribedEvents(): array
        {
            return [
                Events::prePersist,
                Events::preUpdate,
            ];
        }
        // Custom logic
    });
    
  4. Configuration

    • Symfony: Override bundle parameters in config/packages/doctrine_extra.yaml.
    • Laravel: Bind traits to Doctrine’s event system via service providers.
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