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

atheon/doctrine-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require atheon/doctrine-bundle
    

    (Note: This appears to be a repackaged version of doctrine/doctrine-bundle. Verify if this is intentional or a fork. The official package is doctrine/doctrine-bundle.)

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

    return [
        // ...
        Atheon\DoctrineBundle\AtheonDoctrineBundle::class => ['all' => true],
    ];
    
  3. Configure Database: Update config/packages/doctrine.yaml (or create it):

    doctrine:
        dbal:
            url: '%env(DATABASE_URL)%'
        orm:
            auto_generate_proxy_classes: true
            naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
            auto_mapping: true
            mappings:
                App:
                    is_bundle: false
                    type: annotation
                    dir: '%kernel.project_dir%/src/Entity'
                    prefix: 'App\Entity'
                    alias: App
    
  4. First Use Case: Create an entity (e.g., src/Entity/User.php):

    namespace App\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    
    #[ORM\Entity(repositoryClass: "App\Repository\UserRepository")]
    class User
    {
        #[ORM\Id, ORM\GeneratedValue, ORM\Column]
        private ?int $id = null;
    
        #[ORM\Column(length: 255)]
        private string $name;
    

    Run migrations:

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

Implementation Patterns

Common Workflows

  1. Entity Management:

    • Use Doctrine ORM for active record patterns:
      $user = new User();
      $user->setName('John Doe');
      $entityManager->persist($user);
      $entityManager->flush();
      
    • Repositories: Extend Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository for custom queries:
      namespace App\Repository;
      
      use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
      use Doctrine\Persistence\ManagerRegistry;
      
      class UserRepository extends ServiceEntityRepository
      {
          public function __construct(ManagerRegistry $registry)
          {
              parent::__construct($registry, User::class);
          }
      
          public function findByName(string $name): array
          {
              return $this->createQueryBuilder('u')
                  ->where('u.name = :name')
                  ->setParameter('name', $name)
                  ->getQuery()
                  ->getResult();
          }
      }
      
  2. Database Abstraction (DBAL):

    • Use Connection for raw SQL or schema operations:
      $connection = $this->getConnection();
      $users = $connection->fetchAllAssociative('SELECT * FROM user');
      
    • Schema management:
      php bin/console doctrine:schema:update --force
      
  3. Query Builder:

    • Chain methods for dynamic queries:
      $qb = $entityManager->createQueryBuilder();
      $qb->select('u')
         ->from(User::class, 'u')
         ->where('u.name LIKE :name')
         ->setParameter('name', '%John%');
      
  4. Lifecycle Callbacks:

    • Use annotations for pre/post events:
      #[ORM\PrePersist]
      public function setCreatedAt(): void
      {
          $this->createdAt = new \DateTime();
      }
      
  5. Dependency Injection:

    • Inject EntityManagerInterface or Doctrine service:
      public function __construct(private EntityManagerInterface $em) {}
      

Integration Tips

  1. Symfony Forms:

    • Bind entities to forms:
      $form = $this->createForm(UserType::class, $user);
      
    • Use EntityType for dropdowns:
      $builder->add('role', EntityType::class, [
          'class' => Role::class,
          'choice_label' => 'name',
      ]);
      
  2. Validation:

    • Combine with Symfony Validator:
      #[ORM\Entity, Validation\Constraints\Valid]
      class User { ... }
      
  3. APIs (API Platform):

    • Annotate entities for automatic API endpoints:
      #[ApiResource]
      class User { ... }
      
  4. Testing:

    • Use DatabaseTestCase for fixtures:
      use Doctrine\ORM\EntityManagerInterface;
      use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
      
      class UserTest extends KernelTestCase
      {
          private EntityManagerInterface $em;
      
          protected function setUp(): void
          {
              self::bootKernel();
              $this->em = self::$kernel->getContainer()->get('doctrine')->getManager();
          }
      }
      
  5. Caching:

    • Configure doctrine.yaml for query caching:
      orm:
          metadata_cache_driver: apcu
          query_cache_driver: apcu
          result_cache_driver: apcu
      

Gotchas and Tips

Pitfalls

  1. Proxy Classes:

    • Forgetting to clear cache after adding new entities:
      php bin/console cache:clear
      
    • Fix: Ensure auto_generate_proxy_classes is true and proxy_dir is writable.
  2. Naming Conflicts:

    • Case-sensitive table names (e.g., user vs User) can cause issues on some DBs.
    • Fix: Use naming_strategy (e.g., doctrine.orm.naming_strategy.underscore).
  3. Lazy Loading:

    • Accidental N+1 queries in loops:
      foreach ($users as $user) {
          echo $user->getPosts()->count(); // Triggers N+1 queries
      }
      
    • Fix: Use fetch="EAGER" or join in queries.
  4. Migrations:

    • Schema updates may fail if tables exist but are not mapped.
    • Fix: Run doctrine:schema:validate before migrations.
  5. Transaction Management:

    • Forgetting to commit transactions:
      $entityManager->beginTransaction();
      // ... operations
      $entityManager->commit(); // Don't forget this!
      
  6. Circular References:

    • Bidirectional associations without proper inversedBy/mappedBy:
      #[ORM\ManyToMany(targetEntity: User::class, inversedBy: "roles")]
      private Collection $users;
      
    • Fix: Define both sides of the relationship.
  7. Deprecated Features:

    • Using doctrine:generate:entities (deprecated in favor of make:entity).

Debugging Tips

  1. Query Logging: Enable in config/packages/dev/doctrine.yaml:

    dbal:
        logging: true
        profiling: true
    

    View queries in the Profiler (/_profiler).

  2. Doctrine Profiler:

    • Install symfony/web-profiler-bundle for detailed ORM/DBAL stats.
  3. Common Errors:

    • "Class not found": Verify auto_mapping and prefix in doctrine.yaml.
    • "Column not found": Check for typos in @Column or schema updates.
    • "Connection failed": Validate DATABASE_URL in .env.

Extension Points

  1. Custom DQL Functions:

    • Register custom functions in doctrine.yaml:
      orm:
          dql:
              string_functions:
                  CONCAT_WS: App\Doctrine\StringFunctions::concatWs
      
  2. Event Subscribers:

    • Listen to lifecycle events:
      namespace App\EventListener;
      
      use Doctrine\Common\EventSubscriber;
      use Doctrine\ORM\Event\LifecycleEventArgs;
      
      class UserSubscriber implements EventSubscriber
      {
          public function getSubscribedEvents(): array
          {
              return ['prePersist'];
          }
      
          public function prePersist(LifecycleEventArgs $args): void
          {
              $entity = $args->getEntity();
              if ($entity instanceof User) {
                  $entity->setCreatedAt(new \DateTime());
              }
          }
      }
      
  3. Custom Repository Factories:

    • Override repository creation in doctrine.yaml:
      orm:
          repository_factory: App\Doctrine\CustomRepositoryFactory
      
  4. Database Platform Extensions:

    • Extend Doctrine\DBAL\Platforms\AbstractPlatform for custom SQL dialects.
  5. Fixtures:

    • Use `doct
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