Skip to content

Lesson 17 of 45 · Wiring Things Together

The Service Pattern

Intermediate•
lesson•
October 27, 2026•
~8 min read

The word that means nothing

Open any large PHP codebase. Search for Service. You'll find dozens of classes ending in that word. ReservationService, GuestService, BillingService, EmailService, UploadService, ReportService, CalculatorService, ValidatorService. Some of them have one method. Some of them have far more. Some of them have nothing in common except the suffix.

"Service" is used so often, for so many different things, that the word carries no information. Saying "this is a service class" is like saying "this is a class".

What "service" actually means (the original)

Domain-Driven Design (DDD) is a style of modeling software around the business domain. Eric Evans' book on it describes services in three places: the application layer, the domain layer, and infrastructure. A layer is a group of classes that share one kind of job. Reading those as three kinds of service:

  • Application service. A class that orchestrates a use case, which means it calls the other pieces in order. It receives input, calls domain code, talks to repositories, dispatches events, and returns a result. It owns no business state and no business rules. It's the orchestration layer. In the style this course uses it is a command handler or use case handler. This maps to the Service Layer from Fowler's Patterns of Enterprise Application Architecture (the catalog entry is by Randy Stafford).

  • Domain service. A class that contains business logic that doesn't fit naturally on any single entity or value object. The classic example: transferring money between two accounts. Neither account "owns" the transfer; the rule lives between them. The domain service is where it goes.

  • Infrastructure service. A class that talks to the outside world: a mailer, a payment gateway, a search index, a third-party API.

What "service" became

In the PHP codebases I've worked on, the distinctions got lost. "Service" became the default name for "any class that has methods on it that aren't a model".

I think the reason is structural. Laravel's default layout has controllers and models, and anything that fits neither needs somewhere to go. A Services/ folder is the easy answer, and the folder fills up.

The grab-bag service problem

Here's the typical fate of a "service" (a sketch, with the method bodies left out):

PHP
<?php declare(strict_types=1); namespace App\Booking; use App\Billing\Invoice; use Illuminate\Support\Collection; final class GuestService { public function register(array $input): Guest { /* ... */ } public function authenticate(string $email, string $password): ?Guest { /* ... */ } public function changePassword(GuestId $guestId, string $new): void { /* ... */ } public function chargeStayBalance(GuestId $guestId): Invoice { /* ... */ } public function exportPersonalData(GuestId $guestId): string { /* ... */ } public function updatePreferences(GuestId $guestId, array $prefs): void { /* ... */ } public function suspendForViolation(GuestId $guestId, string $reason): void { /* ... */ } public function calculateLoyaltyScore(GuestId $guestId): int { /* ... */ } public function isEligibleForUpgrade(GuestId $guestId): bool { /* ... */ } public function findInactiveGuests(int $days): Collection { /* ... */ } }

Ten methods, several reasons to change, no shared theme except "involves a guest". The class violates the Single Responsibility Principle (SRP), has the cohesion problem, and grew the way grab-bag classes grow: someone needed a place to put a method, the class was sort of related, the method went there.

What "service" usually wants to be

The grab-bag is one of the most frequent shapes I've seen under the name "service". The fix is almost never "split this service into smaller services". It's "recognize that each method here is one of the patterns in this course, and put it where it actually belongs".

A practical decomposition:

  • register is a use case. → RegisterGuestCommandHandler. The handler takes a RegisterGuestCommand, calls Guest::register(...), saves through Guests (the repository), dispatches GuestRegistered. Each ingredient is a thing from earlier lessons.

  • authenticate is a use case. → AuthenticateGuestCommandHandler.

  • changePassword is a use case. → ChangeGuestPasswordCommandHandler. The actual rule "what does it mean to change a password" lives on the Guest entity: $guest->changePassword($newHash, $now).

  • chargeStayBalance is a use case that belongs to a different area of the codebase, with its own model. → ChargeStayBalanceCommandHandler in a billing or payments module, not Booking/. The fact that the original service lumped it with guest operations is the cohesion smell.

  • exportPersonalData is a use case. → ExportGuestPersonalDataCommandHandler. Probably in a separate Privacy/ or Compliance/ module.

  • updatePreferences, suspendForViolation: more use cases.

  • calculateLoyaltyScore is a domain service. The score involves data from multiple sources and doesn't fit on Guest alone. → GuestLoyaltyScoreCalculator (a real, narrow service in the original DDD sense).

  • isEligibleForUpgrade is either a method on Guest (rich model), a domain service, or a specification: a small object that names one business rule.

  • findInactiveGuests is a repository query. → Guests::inactiveSince(...).

When a real service earns its place

After the decomposition, you may still have a few classes that genuinely fit "service". They earn their place when:

  • They contain logic that doesn't fit on any single entity or value object. "Allocate a guest to a room across two adjacent reservations." "Calculate a price using exchange rates from another module." "Score a guest based on data from booking history and billing." These are computational, multi-source, or multi-entity.

  • They're stateless. A real service doesn't carry mutable state between method calls. It takes input, returns output, side effects go through other collaborators (repositories, dispatchers).

  • They have a narrow, specific name. ExchangeRateConverter, GuestLoyaltyScoreCalculator, CancellationFeePolicy. Not GuestService. The name commits to one job.

  • They're injected through dependency injection. They're regular classes with regular dependencies, not magical things reached for from a container.

Here's what one looks like once it's actually earned its place. The grab-bag GuestService earlier in this lesson had a calculateLoyaltyScore(GuestId $guestId): int method with no home. Pulled out on its own, it becomes GuestLoyaltyScoreCalculator: a stateless class that takes a GuestId (the value object that identifies a guest) plus that guest's stay history from booking and lifetime spend from billing, and returns a LoyaltyScore value object instead of a bare int. The weights in the formula are made up for this example.

PHP
<?php declare(strict_types=1); namespace App\Booking; final readonly class LoyaltyScore { public function __construct( public GuestId $guestId, public int $points, ) { } }
PHP
<?php declare(strict_types=1); namespace App\Booking; final readonly class StayHistory { public function __construct( public int $completedStays, public int $totalNightsStayed, public int $cancelledStays, ) { } }
PHP
<?php declare(strict_types=1); namespace App\Billing; final readonly class LifetimeSpend { public function __construct( public Money $amount, ) { } }
PHP
<?php declare(strict_types=1); namespace App\Booking; use App\Billing\LifetimeSpend; final readonly class GuestLoyaltyScoreCalculator { public function calculateFor( GuestId $guestId, StayHistory $stayHistory, LifetimeSpend $lifetimeSpend, ): LoyaltyScore { $points = ($stayHistory->completedStays * 10) + $stayHistory->totalNightsStayed + intdiv($lifetimeSpend->amount->amountInCents, 10_000) - ($stayHistory->cancelledStays * 5); return new LoyaltyScore($guestId, max(0, $points)); } }

It qualifies as a domain service, not a use case and not a method on Guest, because the rule needs data from two modules: stay history from booking and lifetime spend from billing. Neither Guest nor anything in billing holds both, so the rule has no natural home on either. It also depends on nothing from Laravel, Eloquent, or a container: calculateFor takes domain values and returns one, which is what makes it trivial to unit test.

PHP-specific notes

Stop using Service as a default suffix. A class named after what it does (PriceCalculator, EmailVerifier, RefundProcessor, CancellationFeePolicy) is more useful than the same class named with a Service suffix. The suffix doesn't add information.

Application services are command handlers in this style. The handler is the orchestration layer; the command is the input. RegisterGuestCommandHandler and RegisterGuestCommand together cover what a GuestService::register(...) method used to do, with much sharper boundaries.

Domain services are the rarer kind. Many use cases don't need a domain service; the rules fit on entities and value objects. A domain service is what you reach for when you've genuinely tried to put the rule on the entities and it doesn't fit.

Infrastructure services are an interface plus an implementation. A Mailer interface with a MailgunMailer implementation is the infrastructure service pattern. The interface lives in business code; the implementation, called an adapter, lives in infrastructure.

Pitfalls

Renaming a grab-bag without splitting it. I've seen teams rename GuestService to GuestManager or GuestApplicationService and call it a refactor. The class is the same; only the name changed. The fix is splitting by reason to change.

Creating a service for every operation. The other extreme: one class per method, all called XService, sharing nothing. That's just methods with classes wrapped around them. Laravel's Action classes can end up the same way. An action is a class named after one task, like the App\Actions\Fortify\CreateNewUser class that Laravel Fortify copies into your app. The convention comes from the Laravel community (the lorisleiva/laravel-actions package, Spatie's Laravel Beyond CRUD), not from a pattern catalog. An action that loads the data, applies the rule and saves the result itself is a one-method service with a different suffix. A handler is different: it hands the rule to the entity and the loading and saving to the repository. An action built that way is a command handler under another name. The pattern is to organize around use cases (handlers) and concepts (entities, repositories, real services).

Mixing domain and application service. A class that both orchestrates the use case (loads, calls, saves, dispatches) and contains the business rule for what to do is two responsibilities tangled together. Split them: the handler orchestrates, the entity or domain service decides.

Stateful services. A "service" that holds state between method calls, like a cache or a "current guest", is a stateful object under a service name. Dependencies and settings injected through the constructor don't count, because they don't change between calls.

Calling a thing a service when it's actually a value object. A MoneyService with methods like add, format, equals is doing what a Money value object should do. Move the methods to the value object. The service was a workaround for not having one.

The one thing to remember

When you see "Service" in a class name, ask what specific job the class does. If you can answer in a short phrase ("calculates prices", "verifies emails", "issues refunds"), the name should be that, not "Service". If you can't answer in a short phrase, the class is doing too many things, and the right move is to split it.

Course Content