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

Orm Pack Laravel Package

symfony/orm-pack

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   Add the package via Composer (now compatible with broader DBAL versions):
   ```bash
   composer require symfony/orm-pack

This installs Doctrine ORM, Doctrine Bundle, and related dependencies, now supporting Doctrine DBAL v4+ (previously restricted to v3).

  1. Configuration

    • Verify config/packages/doctrine.yaml exists (auto-generated by Symfony Flex).
    • Ensure DATABASE_URL in .env is properly configured (e.g., mysql://user:pass@127.0.0.1:3306/db_name).
    • Note: DBAL version flexibility may require adjustments if using custom types or platform-specific logic.
  2. First Use Case: Create an Entity

    php bin/console make:entity User
    

    Follow prompts to scaffold a User entity. Run migrations:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. Basic CRUD Use the EntityManagerInterface in a controller:

    use Doctrine\ORM\EntityManagerInterface;
    
    public function index(EntityManagerInterface $em)
    {
        $users = $em->getRepository(User::class)->findAll();
        return $this->render('user/index.html.twig', ['users' => $users]);
    }
    

Implementation Patterns

Common Workflows

(Unchanged from previous assessment, but note DBAL v4+ compatibility may affect custom platform logic.)

  1. Repository Pattern Extend Doctrine\ORM\EntityRepository for custom queries:

    namespace App\Repository;
    
    use App\Entity\User;
    use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
    
    class UserRepository extends ServiceEntityRepository
    {
        public function findByEmail(string $email): ?User
        {
            return $this->createQueryBuilder('u')
                ->where('u.email = :email')
                ->setParameter('email', $email)
                ->getQuery()
                ->getOneOrNullResult();
        }
    }
    
  2. Lifecycle Callbacks Use annotations or XML/YAML for entity events:

    use Doctrine\ORM\Mapping as ORM;
    
    #[ORM\Entity]
    class User
    {
        #[ORM\PrePersist]
        public function setCreatedAt(): void
        {
            $this->createdAt = new \DateTime();
        }
    }
    
  3. DQL and QueryBuilder

    • DQL:
      $query = $em->createQuery('SELECT u FROM App\Entity\User u WHERE u.active = :active');
      $query->setParameter('active', true);
      $users = $query->getResult();
      
    • QueryBuilder (type-safe):
      $qb = $em->createQueryBuilder()
          ->select('u')
          ->from(User::class, 'u')
          ->where('u.role = :role')
          ->orderBy('u.name', 'ASC');
      
  4. Transactions Wrap operations in transactions:

    $em->beginTransaction();
    try {
        $em->persist($user);
        $em->flush();
        $em->commit();
    } catch (\Exception $e) {
        $em->rollback();
        throw $e;
    }
    
  5. Symfony Integration

    • Dependency Injection: Inject EntityManagerInterface into services/controllers.
    • Forms: Bind entities to Symfony forms:
      $form = $this->createForm(UserType::class, $user);
      
  6. Fixtures and Testing Use doctrine/doctrine-fixtures-bundle for test data:

    composer require --dev doctrine/doctrine-fixtures-bundle
    php bin/console doctrine:fixtures:load
    

Integration Tips

(Unchanged, but verify custom DBAL logic if upgrading from v3.)

  1. Event Listeners/Subscribers Listen to Doctrine events (e.g., postPersist):

    namespace App\EventListener;
    
    use Doctrine\ORM\Event\LifecycleEventArgs;
    
    class UserListener
    {
        public function postPersist(LifecycleEventArgs $args): void
        {
            $entity = $args->getObject();
            if ($entity instanceof User) {
                $entity->setSlug(strtolower($entity->getName()));
            }
        }
    }
    

    Register in config/services.yaml:

    services:
        App\EventListener\UserListener:
            tags:
                - { name: 'doctrine.event_listener', event: 'postPersist' }
    
  2. Custom DTOs with Hydration Use ResultSetMapping for complex projections:

    $rsm = new ResultSetMapping();
    $rsm->addScalarResult('u.name', 'name');
    $rsm->addScalarResult('COUNT(o.id)', 'orderCount');
    
    $query = $em->createNativeQuery(
        'SELECT u.name, COUNT(o.id) FROM users u LEFT JOIN orders o ON u.id = o.user_id GROUP BY u.id',
        $rsm
    );
    $results = $query->getResult();
    
  3. Caching Enable query caching in config/packages/doctrine.yaml:

    doctrine:
        orm:
            metadata_cache_driver: apcu
            query_cache_driver: apcu
            result_cache_driver: apcu
    
  4. Batch Processing Use DoctrineExtensions for bulk operations:

    composer require stof/doctrine-extensions-bundle
    

    Example with BulkInsert:

    $em->getConnection()->getConfiguration()->setSQLLogger(null);
    $em->getConnection()->beginTransaction();
    $em->getConnection()->executeStatement('INSERT INTO users (...) VALUES (...)');
    $em->getConnection()->commit();
    

Gotchas and Tips

Pitfalls

(Updated for DBAL v4+ compatibility.)

  1. Lazy Loading vs. Eager Loading

    • Pitfall: N+1 query problem with lazy-loaded associations.
    • Fix: Use joinFetch or DISTINCT:
      $qb->select('DISTINCT u')
        ->leftJoin('u.orders', 'o')
        ->addSelect('o');
      
  2. DBAL Version Mismatches

    • Pitfall: Custom platform logic or types may break if relying on DBAL v3-specific features.
    • Fix: Test thoroughly if upgrading from DBAL v3. Check for deprecated methods (e.g., Connection::getWrappedConnection()).
  3. Case Sensitivity in Migrations

    • Pitfall: Schema names/tables are case-sensitive on some DBs (e.g., PostgreSQL).
    • Fix: Use consistent casing in schema.yml or migrations.
  4. Circular References

    • Pitfall: Bidirectional associations without proper inversedBy/mappedBy cause infinite loops.
    • Fix: Always define both sides of a relationship:
      #[ORM\ManyToMany(targetEntity: Role::class, inversedBy: "users")]
      private Collection $roles;
      
  5. Transaction Isolation

    • Pitfall: Long-running transactions block other operations.
    • Fix: Keep transactions short or use READ_COMMITTED isolation.
  6. UTF-8 Collation

    • Pitfall: Missing UTF-8 collation in migrations (e.g., utf8mb4_unicode_ci for MySQL).
    • Fix: Add collation in migrations or DATABASE_URL:
      DATABASE_URL="mysql://user:pass@127.0.0.1:3306/db_name?serverVersion=8.0&charset=utf8mb4&collation=utf8mb4_unicode_ci"
      

Debugging Tips

(Unchanged, but emphasize DBAL version checks.)

  1. Query Logging Enable SQL logging in .env:

    DOCTRINE_DQL_LOGGING_PROFILE=dev
    

    Or in config/packages/dev/doctrine.yaml:

    doctrine:
        orm:
            logging: true
    
  2. Profiler Integration Use Symfony Profiler to inspect queries and entity states:

    $profiler = $this->get('profiler');
    $dataCollector = $profiler->getCollector('doctrine');
    
  3. Common Errors

    • "Class not found": Ensure entities are autoloaded (composer dump-autoload).
    • "Column not found": Verify migration order and schema updates.
    • "Constraint violation": Check for duplicate keys or foreign key violations.
    • DBAL v4+: If using custom types/platforms, check for deprecated methods (e.g., Connection::getWrappedConnection()).

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.
bugban/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin