PHP 8: Modern PHP Development · Databases with PDO
Migrations and ORMs (Doctrine, Eloquent)
Version your schema and know when an ORM helps or hurts.
Migrations are versioned schema changes run in order (Doctrine Migrations, Laravel migrations, Phinx). They make database changes reviewable and reproducible across environments. ORMs map objects to tables: Doctrine ORM uses the Data Mapper pattern (entities are plain objects, an EntityManager persists them); Eloquent uses Active Record (models save themselves). ORMs speed up CRUD but require care with N+1 queries, large batch operations and complex reporting queries, where plain SQL is often better.
<?php
// Doctrine entity with attributes
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ProductRepository::class)]
#[ORM\Table(name: 'products')]
class Product
{
#[ORM\Id, ORM\GeneratedValue, ORM\Column]
private ?int $id = null;
public function __construct(
#[ORM\Column(length: 200)] private string $name,
#[ORM\Column] private int $priceCents,
) {}
}
// Eloquent: avoid N+1 with eager loading
$orders = Order::with('items')->where('status', 'paid')->get();
Common pitfalls
- Editing already-applied migrations instead of adding new ones.
- Lazy loading relationships inside loops.
- Loading 100k entities into memory for a batch job (use iteration/chunking).
Key points
- Migrations version your schema
- Data Mapper (Doctrine) vs Active Record (Eloquent)
- Use SQL for heavy reporting and batch work
Further reading: Doctrine ORM documentation
Practice questions
What's the difference between Active Record and Data Mapper?
Answer
In Active Record (Eloquent), model objects know how to save/load themselves. In Data Mapper (Doctrine), entities are plain objects and a separate mapper/EntityManager handles persistence, keeping the domain decoupled from the database.
Why should applied migrations never be edited?
Answer
Other environments have already run them; edits won't re-run, causing schema drift. Create a new migration for further changes.
Open in the app to mark lessons complete, take notes and track your progress.