Lesson 5 of 45 · Small Objects, Big Impact
Named Constructors
What this pattern actually is
A named constructor is a static method on a class that returns a new instance of that class. It is also called a static factory method. Despite the similar name, it is not the Gang of Four Factory Method pattern, where a superclass declares a creation method and subclasses decide which class gets instantiated. A named constructor needs no inheritance, only a public static function someName(...) that returns new self(...).
That single method does two jobs: it constructs the object, and it gives the construction path a name. The second job is what makes it useful. The default PHP constructor (__construct) has one signature, no name beyond the class name itself, and no way to express what kind of object you're building. Named constructors fix all three.
Here's an example on a data transfer object. It is the evolved version of the RequestReservationData from the Data Transfer Objects lesson: the primitives became value objects and the constructor became private.
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Booking\GuestCount;
use App\Booking\GuestId;
use App\Booking\RoomId;
use App\Http\Requests\RequestReservationRequest;
use App\Pricing\RatePlanCode;
use Carbon\CarbonImmutable;
final readonly class RequestReservationData
{
private function __construct(
public GuestId $guestId,
public RoomId $roomId,
public DateRange $stayDates,
public GuestCount $guestCount,
public RatePlanCode $ratePlanCode,
public ?string $specialRequests,
) {}
public static function fromArray(array $data): self
{
return new self(
guestId: new GuestId($data['guest_id']),
roomId: new RoomId($data['room_id']),
stayDates: new DateRange(
CarbonImmutable::parse($data['check_in']),
CarbonImmutable::parse($data['check_out']),
),
guestCount: new GuestCount(
adults: (int) $data['adults'],
children: (int) ($data['children'] ?? 0),
),
ratePlanCode: new RatePlanCode($data['rate_plan_code']),
specialRequests: $data['special_requests'] ?? null,
);
}
public static function fromRequest(RequestReservationRequest $request): self
{
return self::fromArray($request->validated());
}
}Two named constructors, fromArray() and fromRequest(). fromArray() parses the raw input, fromRequest() hands the form request's validated data to fromArray(), and both end at the same private constructor. You can add as many as the class needs: one per input shape (form request, Eloquent model, channel manager response, webhook payload, CSV row). The construction work lives on the class, not scattered across every caller that happens to want to build one.
GuestId is the class from the Primitive Obsession lesson and RoomId has the same shape, DateRange is built in the Immutable Objects lesson, and RatePlanCode is a string wrapper that validates its format; those are not shown here. GuestCount is a small value object with one way to be built, so a plain public constructor is enough:
<?php
declare(strict_types=1);
namespace App\Booking;
use InvalidArgumentException;
final readonly class GuestCount
{
public function __construct(public int $adults, public int $children)
{
if ($adults < 1) {
throw new InvalidArgumentException('A reservation needs at least one adult');
}
if ($children < 0) {
throw new InvalidArgumentException('Children cannot be negative');
}
}
}Why named constructors matter
The default PHP constructor is anonymous. new Reservation(123, '2026-05-09', '2026-05-12', 'FLEX') tells you nothing about what the four arguments mean. The constructor takes four positional values; if you've memorized the order, you can read it. Otherwise you have to open the class. PHP 8 named arguments (new Reservation(roomId: 123, ...)) label each value, but they still don't say what kind of reservation is being built, or from what.
Named constructors carry intent in the method name itself. RequestReservationData::fromArray($input), RequestReservationData::fromRequest($request) and RequestReservationData::forImport($csvRow) each read as a sentence. The reader doesn't have to guess what kind of object is being built; the method name says so.
A few specific things named constructors give you:
Multiple construction paths. Different inputs (array, request, JSON, model) get different methods. Each method handles its own parsing and defaulting. The class doesn't have one giant constructor with branches inside it.
Documentation by name.
Money::fromCents(100, $usd)versusMoney::fromDollars(1.00, $usd). Both produce the same value object. The name of the construction tells the reader what unit the input was in. The Value Objects lesson showed this onPrice; it's the named-constructor pattern in action.Defaults and parsing in one place. The conversion from the
check_instring toCarbonImmutablelives infromArray. Every consumer who builds aRequestReservationDatafrom raw data goes through the same parsing. Nobody re-implements it.No public constructor pollution. When the named constructors are the only way to build, the primary constructor can be
private. That removes the temptation for someone to callnew RequestReservationData(...)somewhere with the wrong arguments.
Where this pattern earns its place
This approach is good for classes like:
Data transfer objects.
Value objects.
Commands that get dispatched to handlers.
Events that record what happened.
Read models built from a query result.
Practically: any class that doesn't have constructor dependencies (services, repositories, mailers) and is mostly carrying typed data. These classes benefit the most because their job is "be a typed, validated, well-shaped value", and the named constructor is the place to enforce that shape at the entry point.
For classes with dependencies (handlers, services, controllers), constructor injection is the right shape. The dependencies come from the container; you don't construct the handler from JSON.
The private constructor pattern
When a class is built only through named constructors, it makes sense to lock the primary constructor down. This is the full Money the rest of the course uses. The previous lesson introduced it with a public constructor; here the constructor goes private and the class gains the methods later lessons rely on:
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Billing\Exceptions\MismatchedCurrencies;
use InvalidArgumentException;
final readonly class Money
{
private function __construct(
public int $amountInCents,
public Currency $currency,
) {
if ($amountInCents < 0) {
throw new InvalidArgumentException('Money cannot be negative');
}
}
public static function fromCents(int $amountInCents, Currency $currency): self
{
return new self($amountInCents, $currency);
}
public static function fromDollars(float $dollars, Currency $currency): self
{
return new self((int) round($dollars * 100), $currency);
}
public static function zero(Currency $currency): self
{
return new self(0, $currency);
}
public function add(Money $other): self
{
if (!$this->currency->equals($other->currency)) {
throw new MismatchedCurrencies($this->currency, $other->currency);
}
return new self($this->amountInCents + $other->amountInCents, $this->currency);
}
public function multiplyBy(int $factor): self
{
return new self($this->amountInCents * $factor, $this->currency);
}
public function applyDiscountPercent(int $percent): self
{
if ($percent < 0 || $percent > 100) {
throw new InvalidArgumentException('Discount must be between 0 and 100');
}
return new self((int) round($this->amountInCents * (100 - $percent) / 100), $this->currency);
}
public function percentage(int $percent): self
{
return new self(intdiv($this->amountInCents * $percent, 100), $this->currency);
}
public function isZero(): bool
{
return $this->amountInCents === 0;
}
public function equals(Money $other): bool
{
return $this->amountInCents === $other->amountInCents
&& $this->currency->equals($other->currency);
}
public function format(): string
{
return $this->currency->format($this->amountInCents);
}
}Currency gets named constructors too, so callers write Currency::usd() instead of new Currency('USD'). Its constructor stays public, because currency codes also arrive as strings from database rows and user input, and new Currency($code) is the plain way to build one from those:
<?php
declare(strict_types=1);
namespace App\Billing;
use InvalidArgumentException;
final readonly class Currency
{
private const SUPPORTED = ['USD', 'EUR', 'GBP'];
private const SYMBOLS = ['USD' => '$', 'EUR' => '€', 'GBP' => '£'];
public function __construct(public string $isoCode)
{
if (!in_array($isoCode, self::SUPPORTED, true)) {
throw new InvalidArgumentException("Unknown currency: {$isoCode}");
}
}
public static function usd(): self
{
return new self('USD');
}
public static function eur(): self
{
return new self('EUR');
}
public function equals(Currency $other): bool
{
return $this->isoCode === $other->isoCode;
}
public function format(int $amountInCents): string
{
return self::SYMBOLS[$this->isoCode] . number_format($amountInCents / 100, 2);
}
}Money::fromCents(100, Currency::usd()) is one of the public ways in. new Money(100, Currency::usd()) fails with an Error ("Call to private App\Billing\Money::__construct() from global scope"). The only way to get a Money instance is to go through one of the named entry points, each of which has its own intent, and the constructor validates for all of them.
Private primary constructor plus public static factories is a good habit for value objects and data transfer objects that have more than one way in.
Multiple named constructors for one class
Sometimes you want several named constructors on the same class, each expressing a different intent. This Reservation is trimmed to what this lesson needs:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Billing\Currency;
use App\Billing\Money;
use App\Booking\GuestCount;
use App\Booking\GuestId;
use App\Booking\RoomId;
use Carbon\CarbonImmutable;
final class Reservation
{
private function __construct(
public readonly ReservationId $id,
public readonly GuestId $guestId,
public readonly RoomId $roomId,
public readonly DateRange $stayDates,
public readonly GuestCount $guestCount,
public readonly Money $quotedPrice,
private ReservationStatus $status,
) {}
public static function request(
GuestId $guestId,
RoomId $roomId,
DateRange $stayDates,
GuestCount $guestCount,
Money $quotedPrice,
): self {
return new self(
ReservationId::next(),
$guestId,
$roomId,
$stayDates,
$guestCount,
$quotedPrice,
ReservationStatus::Pending,
);
}
/** @param array<string, mixed> $row */
public static function reconstitute(array $row): self
{
return new self(
new ReservationId($row['id']),
new GuestId($row['guest_id']),
new RoomId($row['room_id']),
new DateRange(
CarbonImmutable::parse($row['check_in']),
CarbonImmutable::parse($row['check_out']),
),
new GuestCount(adults: (int) $row['adults'], children: (int) $row['children']),
Money::fromCents((int) $row['price_cents'], new Currency($row['currency'])),
ReservationStatus::from($row['status']),
);
}
public function status(): ReservationStatus
{
return $this->status;
}
}request is the business operation. reconstitute is the persistence layer's path back from a row. A third one, fromChannelManager, would build a reservation from the payload of an external distribution partner such as Booking.com or Expedia. Each one reads what it does, and none of them collide.
Pitfalls
A few common mistakes:
Naming named constructors as create. RequestReservationData::create(...) is a name that adds nothing. Every named constructor "creates". The point of the name is to say how or from what: fromArray, fromRequest, forImport, request. Generic names defeat the entire pattern.
Hiding framework details inside value objects. Money::fromHttpRequest($request) couples a value object to the HTTP layer. The conversion belongs in a data transfer object at the boundary, not inside Money itself. Money should stay pure: it knows about currency and integer cents, not about HTTP.
Static factories that are really services. A static factory that takes five services as arguments is a service in disguise. If construction needs services, do it through a real factory class with injected dependencies or directly in the handler that has the services.
Too many named constructors. If a class has eight different ways to be constructed, that's a signal the class is too big or representing too many things. Maybe there are really three different classes hiding inside one. The coupling and cohesion principles and SRP both apply.
The one thing to remember
SomeClass::fromRequest(...) tells the reader what is being built, and new SomeClass(...) doesn't. The cost is one static method per construction path.
When you find a class with multiple input formats, multiple intents, or one giant constructor doing branches inside it, named constructors are the cleanup that earns its place. A class with one obvious construction path is fine with a single primary constructor.
Related Links
- Factory MethodThe Gang of Four Factory Method pattern, which is a different thing from this lesson's named constructors. Read it to see the difference.
- Replace Constructor with Factory FunctionFowler's refactoring catalog entry for moving construction behind a named function instead of a bare constructor call.
- ConstructorsThe PHP manual page on `__construct`, including notes on property promotion and static factory methods as an alternative.