Lesson 14 of 45 · Wiring Things Together
The Factory Design Pattern
Where named constructors stop
Named constructors are great for value objects, DTOs, commands, and events. They share a common trait: the class doesn't need anything from the outside to be built. Hand it some data, parse the data, return the object.
The pattern hits its limit when construction starts needing more than data. Three situations break the named-constructor model:
The implementation to build depends on runtime input, and building it needs services or data the class can't reach (a payment client configured with the account of the hotel taking the payment). A static method can pick between plain subclasses with a
match, but it has no constructor to receive what building them takes.Construction needs services (a clock, a hasher, an external lookup, a database query). A static method can only reach a service by fetching it from the container, which is the service location, or by making every caller pass it in.
The construction logic is too big to live on the class as a static method without obscuring what the class is.
In any of these, you reach for a separate class whose only job is to build instances of another class: the Factory Pattern.
What the Factory Pattern is
The version in this lesson is usually called a Simple Factory: a plain class whose methods build and return objects. The Gang of Four's Factory Method, where subclasses decide which class gets created, is a different pattern. Abstract Factory comes up below.
The first example builds one of several implementations from runtime input. The hotel company in this course runs several properties, and each property has its own payment account, sometimes with a different provider. The container can't build that Payments object at boot, because the provider and the API key depend on which property is taking the payment. The account details come from a lookup:
<?php
declare(strict_types=1);
namespace App\Payments;
final readonly class PaymentAccount
{
public function __construct(
public PaymentProvider $provider,
public string $apiKey,
public string $merchantAccount,
) {}
}<?php
declare(strict_types=1);
namespace App\Payments;
use App\Booking\PropertyId;
interface PaymentAccounts
{
public function forProperty(PropertyId $propertyId): PaymentAccount;
}PaymentProvider is an enum with Stripe and Adyen cases. The factory reads the account and builds the matching implementation of the Payments interface from the Decorator Pattern lesson:
<?php
declare(strict_types=1);
namespace App\Payments;
use App\Booking\PropertyId;
use Stripe\StripeClient;
final readonly class PaymentsFactory
{
public function __construct(private PaymentAccounts $accounts) {}
public function forProperty(PropertyId $propertyId): Payments
{
$account = $this->accounts->forProperty($propertyId);
return match ($account->provider) {
PaymentProvider::Stripe => new StripePayments(new StripeClient($account->apiKey)),
PaymentProvider::Adyen => new AdyenPayments($account->apiKey, $account->merchantAccount),
};
}
}StripePayments is the adapter from the Decorator Pattern lesson, which takes a StripeClient; here each property gets a client built with its own key. AdyenPayments is trimmed away; it implements Payments too and takes the API key plus the merchant account Adyen asks for.
The handler asks the factory for "the payments implementation for this property" and gets back something it can use without caring which provider it is. Adding a provider is one enum case, one class and one match arm. The Strategy Pattern lesson uses a smaller version of this shape, where the implementations already exist and the factory only picks one.
Factories that need services
The other common use builds only one class, but building it needs services. Issuing an invoice for a stay is one case. Three things go into a new invoice that the Invoice class can't produce itself: the next number from the invoice sequence, the tax rate for the property the room belongs to, and the issue date. Each comes from a service:
<?php
declare(strict_types=1);
namespace App\Billing;
interface InvoiceNumbers
{
public function next(): InvoiceNumber;
}<?php
declare(strict_types=1);
namespace App\Billing;
use App\Booking\RoomId;
interface TaxRates
{
public function forRoom(RoomId $roomId): TaxRate;
}InvoiceNumber wraps a string. TaxRate is a value object holding a percentage, with a taxOn(Money $net): Money method. The Invoice here is trimmed to what this lesson needs, and its named constructor owns the rule that the tax comes from the rate:
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Reservations\ReservationId;
use DateTimeImmutable;
final readonly class Invoice
{
private function __construct(
public InvoiceNumber $number,
public ReservationId $reservationId,
public Money $net,
public Money $tax,
public DateTimeImmutable $issuedAt,
) {}
public static function issue(
InvoiceNumber $number,
ReservationId $reservationId,
Money $net,
TaxRate $taxRate,
DateTimeImmutable $issuedAt,
): self {
return new self($number, $reservationId, $net, $taxRate->taxOn($net), $issuedAt);
}
}The factory gathers the inputs and hands them to Invoice::issue():
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Reservations\Reservation;
use Psr\Clock\ClockInterface as Clock;
final readonly class InvoiceFactory
{
public function __construct(
private InvoiceNumbers $numbers,
private TaxRates $taxRates,
private Clock $clock,
) {}
public function issueFor(Reservation $reservation): Invoice
{
return Invoice::issue(
$this->numbers->next(),
$reservation->id,
$reservation->quotedPrice,
$this->taxRates->forRoom($reservation->roomId),
$this->clock->now(),
);
}
}Invoice::issue() can't do this gathering. It has no constructor to receive InvoiceNumbers or TaxRates, and fetching them from the container inside it would be service location.
Checking a guest out and billing a no-show both create invoices. Each handler receives InvoiceFactory through its constructor and calls issueFor($reservation). Drawing the next number, looking up the tax rate and reading the clock happen in one class, so a second caller can't skip the sequence or stamp the wrong date.
The Abstract Factory variant
You'll see the Abstract Factory in pattern catalogs. The pattern is one factory interface that builds families of related objects, with different concrete factories for different contexts (production, test, regional variants).
In practice, in modern PHP with a dependency-injection container, you rarely write Abstract Factories explicitly. The container does that job. You bind different concrete implementations of an interface in different environments, and the rest of the code asks for the interface.
If you do find yourself writing one, it's usually because a whole family of implementations has to switch together at runtime (one property's payments, tax and invoicing adapters all coming from the same provider), which is more than one match in a factory like PaymentsFactory covers. That case is rare.
Eloquent factories: a different thing with the same name
ReservationModel::factory()->create() (Eloquent factories) is not the same Factory Pattern this lesson is about.
Eloquent factories are a testing tool for generating model rows with realistic-looking fake data. They sit at the database boundary; they're for tests, seeders, and demo data. The Factory Pattern is for production runtime construction logic.
Pitfalls
A few common mistakes when reaching for factories:
Factory of one. A factory class with one method that builds one kind of object using no services and no decisions is just a worse named constructor. If GuestFactory::build($id, $email) does nothing the constructor wouldn't do, delete the factory. Use a named constructor or the regular constructor.
Factory for things that should be DTOs. If your factory's job is to convert an array into an object and it needs no services, that belongs in the DTO's fromArray, not in a factory.
Factory hiding service location. A factory that calls app(...) inside is service location with a wrapper. The factory should receive its dependencies via DI, the same as any other class. If the factory is reaching into the container, the factory itself isn't injected properly.
Factory explosion. A factory for every class is the overcorrection. For a Guest with a couple of fields, the regular constructor is fine.
Misnamed methods. GuestFactory::create($id, $email) is fine. GuestFactory::createGuest($id, $email) is verbose; the class name already says what's being built. Keep method names short: build, for, make, or a domain verb when it reads better at the call site.
The one thing to remember
When you find construction logic that needs services, makes runtime decisions, or grows beyond a few lines, that logic wants to live in its own class. The factory class is the natural home. The thing being built stays small and clean. The factory carries the assembly knowledge.
A "factory" that does none of those things is a misnamed DTO or a wrapped constructor. In a small CRUD project, named constructors are enough.
Related Links
- Factory Method (Refactoring.Guru)Walks through the Factory Method pattern with a diagram and a worked example, the GoF pattern where subclasses decide what to create. The factory classes in this lesson are a simpler cousin of it.
- Abstract Factory (Refactoring.Guru)Covers the Abstract Factory variant for producing families of related objects, mentioned in this lesson's section on the pattern.
- Eloquent: Factories (Laravel Docs)Laravel's own docs for model factories, the testing helper that shares a name with this pattern but does a different job.
- Service Container (Laravel Docs)Shows how the container injects dependencies, the same mechanism a well-built factory class should use for its own dependencies.