Course › Day 7 · Production › Scene 47 of 49 · 25 min
A new developer asks how it all fits together
One booking end to end, where code goes, the container inside, Pint, Larastan, arch tests, mutation testing, Rector, upgrades
On this page
#devMonday 10:00
Amira · developer, first weekI’ve read the code for two days. Three questions. What happens between a host pressing Book and the guest getting an email? Where do I put new code? And what has to pass before I push?
Sara · tech leadGood questions, in a good order. Let’s go through one booking, then the rules, then the checks. The checks already found something this morning, so you’ll see one fixed.
Where code goes
The folders are by domain, not by kind: a new feature about pricing goes next to the rest of pricing.
app/
├── Accounts/ InviteMember, AcceptInvitation, RemoveMember
├── Bookings/ CreateBooking, ChangeBookingDates, MoveBooking, CancelBooking, Stay (value), States/, Refunds/
├── Channels/ CalendarSync (the coordinator), ChannelManager, Airbnb/, BookingCom/, Ical/
├── Exports/ AccountExport and its three exports
├── Messaging/ send times, scheduling, templates and their variables
├── Money/ Money, Currency (values)
├── Operations/ PlanTurnover
├── Payments/ the gateway, Stripe, events, reconciliation
├── Pricing/ PriceQuoter, QuoteBuilder, NightlyRates, the caching proxy
├── Properties/ DuplicateProperty, search and its two repositories
├── Http/ Controllers, Requests, Resources, Middleware: HTTP only
├── Jobs/ Events/ Listeners/ Notifications/ Observers/ Policies/ Console/ Models/ Providers/
| Kind of code | Goes in | Rule |
|---|---|---|
| Who may do it | a Policy | never an if in a controller |
| Is the input valid | a Form Request | shape and simple rules; business rules ask the model (stayTooShort()) |
| One thing a user or a system does | an action, in its domain folder | one public method; owns its transaction and its locks |
| What a value is | a value object (Money, Stay) | immutable, validated when created |
| Relations, casts, query rules | the model | scopes for rules that are queries (availableFor()) |
| What must follow a calendar change, in order | CalendarSync, called directly | a direct call when the steps must all happen and their order matters |
| Reactions that don’t depend on each other | an event and its listeners | scene 22’s BookingCancelled: each listener can fail alone |
| Anything slow or external | a queued job, after commit | with tries, backoff, a timeout and failed() |
Actions, services, repositories. An action is one use case (CreateBooking). A "service" that collects ten unrelated methods (BookingService) is where code goes to be forgotten; this app has none. A repository appears once, where two stores really answer the same question (scene 43).
Laravel inside: how the container builds an action
No action in this app is built with new. The controller asks for CreateBooking; the container reads its constructor, sees PriceQuoter and CalendarSync, builds those the same way, and so on down: PriceQuoter needs NightlyPrices, an interface, which AppServiceProvider binds to NightlyRates (scene 35). That recursion is the whole trick:
public function build($concrete)
{
$reflector = new ReflectionClass($concrete);
$constructor = $reflector->getConstructor();
if ($constructor === null) {
return new $concrete; // no dependencies: done
}
$dependencies = array_map(
fn (ReflectionParameter $parameter) => $this->make($parameter->getType()->getName()), // each type, built the same way
$constructor->getParameters(),
);
return $reflector->newInstanceArgs($dependencies);
}
make() checks the bindings first: a singleton() returns the one instance (scene 5), a contextual binding gives QuoteController’s constructor the cached rates (scene 35), an interface without a binding is an error at once. Everything else is built by reading its constructor.
That is why every class here takes its dependencies in the constructor and none of them calls app() inside a method: the dependencies are visible, and a test can pass different ones. Jobs and Form Requests get theirs as arguments of handle() and rules(). The one exception is a queued notification (scene 24): it is serialized and rebuilt by the queue, so there is no constructor to inject into, and it resolves its renderer when it runs.
What must pass before a push
Five checks, all run by CI on every push (scene 45), and all runnable on a laptop in under a minute.
1. Pint: one code style, never discussed in review
{
"preset": "laravel",
"rules": {
"concat_space": { "spacing": "one" }
}
}
vendor/bin/pint fixes the style; vendor/bin/pint --test only checks it, which is what CI runs.
2. Larastan: types checked without running the code
includes:
- vendor/larastan/larastan/extension.neon
- phpstan-baseline.neon
parameters:
paths:
- app
level: 8
Larastan teaches PHPStan Laravel’s magic: relations, scopes, facades. Level 8 includes null safety: $property->ratePlan->name is an error, because the plan can be null; $property->ratePlan?->name is fine.
A codebase that never ran it finds hundreds of errors on the first run. vendor/bin/phpstan --generate-baseline records today’s errors in phpstan-baseline.neon, so CI fails only on new ones, and the baseline shrinks as code is touched.
3. Architecture tests: the rules above, as tests
<?php
use Illuminate\Database\Eloquent\Model;
use Symfony\Component\Finder\Finder;
arch('debugging calls never reach production')
->expect(['dd', 'dump', 'var_dump', 'ray'])
->not->toBeUsed();
arch('env() is read in config files only') // under config:cache, env() returns null (scene 45)
->expect('env')
->not->toBeUsed();
arch('controllers only speak HTTP: no queries, no transactions')
->expect('App\Http\Controllers')
->not->toUse('Illuminate\Support\Facades\DB');
arch('models are Eloquent models')
->expect('App\Models')
->toExtend(Model::class);
it('keeps no static state in app classes, which long-running workers would keep forever', function () {
$offenders = [];
foreach (Finder::create()->files()->in(app_path())->name('*.php') as $file) {
$class = 'App\\' . str_replace(['/', '.php'], ['\\', ''], $file->getRelativePathname());
if (! class_exists($class) && ! trait_exists($class)) {
continue; // interfaces and enums have no properties
}
foreach ((new ReflectionClass($class))->getProperties(ReflectionProperty::IS_STATIC) as $property) {
if ($property->getDeclaringClass()->getName() === $class) {
$offenders[] = "{$class}::\${$property->getName()}";
}
}
}
expect($offenders)->toBe([]); // scene 46's postmortem, action 4
});
The first run this morning failed once: AcceptInvitationController from scene 20 uses DB::transaction(). It is fixed below.
What the architecture test found
Scene 20 put the acceptance in the controller, with its transaction, and checked accepted_at before the transaction: two clicks on the link at once both passed the check. As an action it locks the invitation first, so the second click finds it already used:
<?php
namespace App\Accounts;
use App\Models\AccountInvitation;
use App\Models\User;
use Illuminate\Support\Facades\DB;
final class AcceptInvitation
{
public function handle(AccountInvitation $invitation, User $user): void
{
DB::transaction(function () use ($invitation, $user): void {
$invitation = AccountInvitation::whereKey($invitation->id)->lockForUpdate()->firstOrFail(); // two clicks: one waits here
if ($invitation->accepted_at !== null) {
throw InvitationNotUsable::alreadyUsed();
}
if (mb_strtolower($user->email) !== $invitation->email) {
throw InvitationNotUsable::forAnotherEmail();
}
$invitation->account->users()->syncWithoutDetaching([$user->id => ['role' => $invitation->role->value]]);
$invitation->forceFill(['accepted_at' => now()])->save();
$user->forceFill(['current_account_id' => $invitation->account_id])->save();
});
}
}
The action says what went wrong in its own words. The exception knows its status code (as in scene 33), so the action never mentions HTTP:
<?php
namespace App\Accounts;
use Illuminate\Http\JsonResponse;
use RuntimeException;
/** An invitation that exists but can't be accepted by this user now. Laravel renders it with its status. */
final class InvitationNotUsable extends RuntimeException
{
private function __construct(string $message, private readonly int $status)
{
parent::__construct($message);
}
public static function alreadyUsed(): self
{
return new self('This invitation was already used.', 410);
}
public static function forAnotherEmail(): self
{
return new self('This invitation is for another email address.', 403);
}
public function render(): JsonResponse
{
return response()->json(['message' => $this->getMessage()], $this->status);
}
}
<?php namespace App\Http\Controllers; use App\Accounts\AcceptInvitation;use App\Models\AccountInvitation;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;use Illuminate\Support\Facades\DB; class AcceptInvitationController extends Controller{ public function __invoke(Request $request, AccountInvitation $invitation): RedirectResponse { $user = $request->user(); abort_if($invitation->accepted_at !== null, 410, 'This invitation was already used.'); abort_if(mb_strtolower($user->email) !== $invitation->email, 403, 'This invitation is for another email address.'); DB::transaction(function () use ($invitation, $user): void { $invitation->account->users()->syncWithoutDetaching([$user->id => ['role' => $invitation->role->value]]); $invitation->forceFill(['accepted_at' => now()])->save(); $user->forceFill(['current_account_id' => $invitation->account_id])->save(); }); public function __invoke(Request $request, AccountInvitation $invitation, AcceptInvitation $accept): RedirectResponse { $accept->handle($invitation, $request->user()); // 410 or 403 from the action, as before return redirect('/dashboard'); }}
4. Mutation testing: do the tests notice when the code is wrong?
Coverage says a line ran during the tests; it doesn’t say a test would fail if the line were wrong. pest --mutate changes the code in small ways (< to <=, -$x to $x, a removed line) and runs the tests against each change. A change no test notices is a gap. One line in a test file says which class it covers:
<?php use App\Money\Money; mutates(Money::class); // pest --mutate changes this class, and only it it('multiplies exactly, with no lost cent', function () { expect(Money::of(15_010, 'EUR')->times(3)->amount)->toBe(45_030); // the incident});21 unchanged lines
it('never changes the original', function () { $nightly = Money::of(15_010, 'EUR'); $nightly->times(3); expect($nightly->amount)->toBe(15_010);}); it('refuses to mix currencies', function () { Money::of(100, 'EUR')->add(Money::of(100, 'EGP'));})->throws(LogicException::class, "Can't combine EUR with EGP."); it('compares by value', function () { expect(Money::of(45_030, 'EUR')->equals(Money::of(45_030, 'EUR')))->toBeTrue() ->and(Money::of(45_030, 'EUR')->equals(Money::of(45_030, 'USD')))->toBeFalse();}); it('formats with the currency’s own decimals', function (int $amount, string $currency, string $shown) { expect(Money::of($amount, $currency)->format())->toBe($shown);})->with([ [45_030, 'EUR', '€450.30'], [15_010, 'JPY', '¥15,010'],]); it('rounds a negative percentage away from zero, so a discount stays negative', function () { expect(Money::of(-101, 'EUR')->percent(5_000)->amount)->toBe(-51); // -50.5 cents: the mutant made it +51});
$ vendor/bin/pest tests/Unit/MoneyTest.php --mutate
UNTESTED app/Money/Money.php > Line 44: UnaryMinusToNegated
- return new self($product < 0 ? -$rounded : $rounded, $this->currency);
+ return new self($product < 0 ? $rounded : $rounded, $this->currency);
Mutations: 1 untested, 23 tested
No test multiplied a negative amount by a percentage, so a discount (scene 7) could have turned positive without a single failure. The last test in the file above was written for it, and the next run reports 24 of 24.
5. Rector: changes across the whole codebase, done by a tool
<?php
use Rector\Config\RectorConfig;
return RectorConfig::configure()
->withPaths([__DIR__ . '/app', __DIR__ . '/tests'])
->withPhpSets() // the PHP version in composer.json: readonly, match, first-class callables …
->withPreparedSets(deadCode: true, typeDeclarations: true);
vendor/bin/rector --dry-run shows the changes; without --dry-run it makes them, and the tests decide whether they stay. For Laravel upgrades, driftingly/rector-laravel adds the rename sets for each major version. A major upgrade is then: read the upgrade guide, raise the version in composer.json, run Rector’s set for that version, run the tests, deploy to staging, one major version at a time.
CI runs all five
name: CI
on: [push, pull_request]
jobs:
tests:
runs-on: ubuntu-24.04
services:
mysql:
image: mysql:8.4
env: { MYSQL_ROOT_PASSWORD: secret, MYSQL_DATABASE: pms_test }
ports: ['3306:3306']
options: --health-cmd="mysqladmin ping -psecret" --health-interval=5s
redis:
image: redis:7.4
ports: ['6379:6379']
meilisearch:
image: getmeili/meilisearch:v1.11
env: { MEILI_MASTER_KEY: ci-key }
ports: ['7700:7700']
env:
DB_HOST: 127.0.0.1
DB_PASSWORD: secret
REDIS_HOST: 127.0.0.1
MEILISEARCH_HOST: http://127.0.0.1:7700
MEILISEARCH_KEY: ci-key
steps:
- uses: actions/checkout@v4
- uses: shivammathur/setup-php@v2
with: { php-version: '8.4', extensions: 'pdo_mysql, redis, pcntl', coverage: none }
- run: composer install --no-interaction --prefer-dist
- run: cp .env.example .env && php artisan key:generate
- run: vendor/bin/pint --test # style
- run: vendor/bin/phpstan analyse --no-progress # types, against the baseline
- run: vendor/bin/rector --dry-run # fails if Rector would still change something
- run: vendor/bin/pest --parallel # tests, architecture tests included
- run: vendor/bin/pest --mutate --parallel --min=90 # at least 90% of mutations caught
Remember
- Code has a home by kind: thin controllers, rules in actions and models, outside services behind clients.
- Let tools enforce the rules: Pint, Larastan, arch tests and mutation tests in CI.
Amira ships her first change on Wednesday. Next: the interview, where all of this has to be explained out loud, on a whiteboard.