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

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer (included in symfony/orm-pack):

    composer require symfony/orm-pack
    

    This pulls in Doctrine ORM, Doctrine Bundle, and related dependencies.

  2. Configuration

    • Ensure config/packages/doctrine.yaml exists (auto-generated by Symfony Flex).
    • Verify DATABASE_URL in .env is properly configured (e.g., mysql://user:pass@127.0.0.1:3306/db_name).
  3. First Use Case: Create an Entity

    php bin/console make:entity User
    

    Follow prompts to scaffold a User entity with fields like name (string) and email (string). Run migrations:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  4. Basic CRUD Use the EntityManager 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

  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 to hook into 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 (Doctrine Query Language):
      $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 a transaction for atomicity:

    $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

  1. Event Listeners/Subscribers Listen to Doctrine events (e.g., postPersist) for cross-cutting logic:

    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); // Disable logging
    $em->getConnection()->beginTransaction();
    $em->getConnection()->executeStatement('INSERT INTO users (...) VALUES (...)');
    $em->getConnection()->commit();
    

Gotchas and Tips

Pitfalls

  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. 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.
  3. 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;
      
  4. Transaction Isolation

    • Pitfall: Long-running transactions block other operations.
    • Fix: Keep transactions short or use READ_COMMITTED isolation.
  5. Entity Manager Clearing

    • Pitfall: $em->clear() removes all managed entities (including those in the current request).
    • Fix: Clear only specific entities or use EntityManagerInterface::getRepository()->find() to reload.
  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

  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 (check composer dump-autoload).
    • "Column not found": Verify migration order and schema updates.
    • "Constraint violation": Check for duplicate keys or foreign key violations.

Extension Points

  1. Custom Types Create a custom Doctrine type for domain-specific logic:
    namespace App\Doctrine\Types;
    
    use Doctrine\DBAL\Platforms\AbstractPlatform;
    use Doctrine\DBAL\Types\Type;
    
    class JsonType extends Type
    {
        public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
        {
            return 'JSON';
        }
    
        public function getName()
        {
            return 'json';
        }
    }
    
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