MARY.WIN

RUSTY — LARAVEL TO RUST — 16

What Laravel's developer experience
can teach Rust

Turn a correct operation into a small, discoverable interface.
Tutorial 16 of 16 in From Laravel to Rust. Before you start: The complete series.

Can a caller construct a valid request and preview it without knowing the implementation details? In examples/src/bin/ep16.rs, RunRequest::new() validates a title. show() accepts a preview capability and a borrowed request. TextPreview produces the display text.

The caller needs three discoverable steps: construct a RunRequest, handle RequestError::EmptyTitle, and pass a valid request to show(). Laravel’s emphasis on named operations and runnable examples provides a useful standard for presenting this Rust API.

A compiling signature still needs clear parameter meanings and an obvious construction path. RunRequest gives the title a domain name. Its constructor states the empty-title rule. The Previewer contract states the behavior required by show().

Before running the example, predict the preview of " tests ". Then predict the constructor result for a blank string. The assertions check both outcomes.

This lesson covers the entrance to a piece of Rust code: a validating constructor, a borrowed accessor, and a one-method trait, and what Laravel's attention to developer experience suggests about each. A caller of this code needs three discoverable steps: construct a RunRequest, handle RequestError::EmptyTitle, and pass a valid request to show(). The lesson closes the series with the evidence attached to three named examples: the borrowed preview from Tutorial 1, the executor-prefix assertion from Tutorial 9, and the HTTP tests from Tutorial 15. It leaves out packaging and publishing a crate. It assumes the whole series.

Take a look at Example 1.

Example 1. Complete example (examples/src/bin/ep16.rs)

#[derive(Debug, PartialEq)]
enum RequestError { EmptyTitle }

struct RunRequest { title: String }
impl RunRequest {
    fn new(title: impl Into<String>) -> Result<Self, RequestError> {
        let title = title.into().trim().to_owned();
        if title.is_empty() { return Err(RequestError::EmptyTitle); }
        Ok(Self { title })
    }
    fn title(&self) -> &str { &self.title }
}

trait Previewer { fn preview(&self, request: &RunRequest) -> String; }

struct TextPreview;
impl Previewer for TextPreview {
    fn preview(&self, request: &RunRequest) -> String {
        format!("Would run: {}", request.title())
    }
}

fn show(previewer: &dyn Previewer, request: &RunRequest) -> String {
    previewer.preview(request)
}

fn main() {
    let request = RunRequest::new(" tests ").unwrap();
    assert_eq!(show(&TextPreview, &request), "Would run: tests");
    assert!(matches!(RunRequest::new(" "), Err(RequestError::EmptyTitle)));
    assert_eq!(request.title(), "tests");
    println!("{}", show(&TextPreview, &request));
}

Before you run it, predict the preview of " tests ", and then the constructor result for a blank string. The assertions check both.

Expected output:

TERMINAL
cargo run --quiet --bin ep16
Would run: tests

The blank title

The call RunRequest::new(" ") held that a string was a title as long as it had something in it. It had one character, a space, and it sat in the second assertion of main, inside matches!. new turned it into an owned String, trimmed it, and found nothing left. It returned Err(RequestError::EmptyTitle), and no RunRequest was made.

Sometimes a signature compiles and still leaves the caller guessing what each parameter means and how to build a valid value. Laravel's emphasis on named operations and runnable examples is a useful standard for that problem. Take another look at Example 1.

There are four pieces. RunRequest::new(title: impl Into<String>) converts its input into an owned string, trims surrounding whitespace, and rejects an empty result with RequestError::EmptyTitle; RunRequest gives the title a domain name, and the constructor states the empty-title rule. The title() accessor returns a &str borrowed from the request. The Previewer trait states the behavior show() requires, and TextPreview::preview() formats the borrowed title into an owned output string. And show(previewer: &dyn Previewer, request: &RunRequest) declares both of its dependencies in its signature, then calls previewer.preview(request) through the trait object.¹

In main, show(&TextPreview, &request) borrows the previewer and the request, and returns Would run: tests once the constructor has normalized " tests ". The terminal prints that same preview, and a separate assertion rejects the blank title. These calls construct and format local values.

A generic implementation of show could express the same capability requirement. This version makes the caller's choice of previewer visible at the call site.

What to borrow from Laravel

Borrow the attention to names. A user should be able to tell preview from execute, validate from persist, and enqueue from complete.

Borrow the attention to examples. A short runnable example explains an API more accurately than a page of adjectives. Include the failure path a new user is likely to meet.

Borrow the attention to workflows. Formatting, tests, linting, and one obvious local run command should be documented together.

Borrow the attention to defaults. A default helps when it is bounded and reversible. If a choice changes storage, security, billing, or network behavior, the default deserves a stronger explanation.

What is not developer experience?

Fewer lines are not less work for the reader, since a single line that depends on five hidden registrations can be harder to follow than a few explicit constructor calls, and, in the other direction and with the same confidence, twenty hand-written wiring files can bury a small framework application, so that line count, which is the measurement nearest to hand, tells you about neither case.

Ask what a maintainer must know to make the next likely change. Can they find the behavior? Can they replace the real dependency at the real entry point? Can they observe failure? Can they run a check that would detect a broken result?

Those questions connect this series to the design-patterns notes, Patterns Under Pressure. A pattern is worth using when it makes a real change or invariant easier to manage; naming it supplies no such evidence. The source package carries one listing from those notes that builds on this tutorial's Previewer. Take a look at Examples 2 and 3, where a PrefixPreview wraps another previewer, once in Rust and once in PHP.

Example 2. Wrapping a previewer (pattern_lab.rs)

#[derive(Debug, PartialEq)]
enum RequestError { EmptyTitle }

struct RunRequest { title: String }
impl RunRequest {
    fn new(title: &str) -> Result<Self, RequestError> {
        let title = title.trim();
        if title.is_empty() { return Err(RequestError::EmptyTitle); }
        Ok(Self { title: title.into() })
    }
}

trait Previewer {
    fn preview(&self, request: &RunRequest) -> String;
}

struct TextPreview;
impl Previewer for TextPreview {
    fn preview(&self, request: &RunRequest) -> String {
        format!("Would run: {}", request.title)
    }
}

struct PrefixPreview<P> { inner: P, prefix: String }
impl<P: Previewer> Previewer for PrefixPreview<P> {
    fn preview(&self, request: &RunRequest) -> String {
        format!("{}{}", self.prefix, self.inner.preview(request))
    }
}

fn show(previewer: &dyn Previewer, request: &RunRequest) -> String {
    previewer.preview(request)
}

fn main() {
    let request = RunRequest::new(" tests ").unwrap();
    let previewer = PrefixPreview {
        inner: TextPreview,
        prefix: "[local] ".into(),
    };
    assert_eq!(show(&previewer, &request), "[local] Would run: tests");
    assert_eq!(request.title, "tests");
    assert!(matches!(RunRequest::new(" "), Err(RequestError::EmptyTitle)));
    println!("{}", show(&previewer, &request));
}

Expected output:

TERMINAL
cargo run --quiet --bin pattern_lab
[local] Would run: tests

Example 3. The same wrapper in PHP (pattern-lab.php)

<?php
declare(strict_types=1);

final readonly class RunRequest
{
    public string $title;

    public function __construct(string $title)
    {
        $title = trim($title);
        if ($title === '') {
            throw new InvalidArgumentException('Empty title');
        }
        $this->title = $title;
    }
}

interface Previewer
{
    public function preview(RunRequest $request): string;
}

final class TextPreview implements Previewer
{
    public function preview(RunRequest $request): string
    {
        return 'Would run: '.$request->title;
    }
}

final readonly class PrefixPreview implements Previewer
{
    public function __construct(
        private Previewer $inner,
        private string $prefix,
    ) {}

    public function preview(RunRequest $request): string
    {
        return $this->prefix.$this->inner->preview($request);
    }
}

function show(Previewer $previewer, RunRequest $request): string
{
    return $previewer->preview($request);
}

$request = new RunRequest(' tests ');
$previewer = new PrefixPreview(new TextPreview(), '[local] ');
assert(show($previewer, $request) === '[local] Would run: tests');
assert($request->title === 'tests');

$rejected = false;
try {
    new RunRequest(' ');
} catch (InvalidArgumentException) {
    $rejected = true;
}
assert($rejected);
echo show($previewer, $request), PHP_EOL;

Expected output:

TERMINAL
php -d zend.assertions=1 -d assert.exception=1 pattern-lab.php
[local] Would run: tests

In both, show is unchanged. It still asks for a Previewer and receives one.

What the series can show

Return to the first tutorial's moved value. We can now explain why preview should borrow an action, why a background request might need to own a snapshot, and why a result should distinguish rejection from successful work. The evidence is attached to named examples, so take them one at a time.

First, the two preview functions from Tutorial 1. In compile-fail/fail01.rs, preview takes an Action:

fn preview(action: Action) {
    println!("{}", action.title);
}

In ep01.rs, it takes an &Action:

fn preview(action: &Action) -> &str {
    &action.title
}

The first version is refused where main uses action after the call:

OUTPUT
error[E0382]: borrow of moved value: `action`
  --> compile-fail/fail01.rs:10:20
   |
 8 |     let action = Action { title: "Run tests".into() };
   |         ------ move occurs because `action` has type `Action`, which does not implement the `Copy` trait
 9 |     preview(action);
   |             ------ value moved here
10 |     println!("{}", action.title);
   |                    ^^^^^^^^^^^^ value borrowed here after move

The borrowed version runs, and its caller still has the action afterward:

TERMINAL
cargo run --quiet --bin ep01
preview: Run tests
still available: Run tests

Second, the executor-prefix assertion from Tutorial 9. The caller assembles a Runner around a fake executor and checks that the fake's prefix comes back:

    let probe = Runner::new(RecordingFake {
        prefix: "chosen by test".into(),
    });
    assert_eq!(probe.run("tests"), "chosen by test: tests");

Third, the capstone's passing HTTP tests from Tutorial 15:

OUTPUT
test tests::creates_then_lists_the_normalized_record ... ok
test tests::rejects_malformed_json ... ok
test tests::rejects_blank_and_overlong_titles_without_inserting ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Each check establishes a particular behavior. None establishes the entire application's correctness. We can also say where Rust's guarantees stop. A memory-safe program can have the wrong business rule. A tested fake can conceal a broken adapter. An in-memory task can disappear on restart.

So the interface is small and its checks pass. Now look at one operation in a Laravel application you work on. Could a new caller tell what it does from its name? Which of its failures would that caller see, and which would they have to find in a log? Is there a check that would fail if it broke?

Testing

Start from memory. Explain the RunRequest path: normalize the title, reject empty input, borrow the valid request, and format a preview. Then compare your explanation with Example 1. Its main asserts three things: the preview text for a valid request, the EmptyTitle refusal for a blank one, and the normalized title through the accessor. The second is the failure path a new user meets first, and it is in the example for that reason.

Then the final exercise. Choose one operation from a Laravel application you can inspect. Write down its input, its ordinary absence, its recoverable failure, its ownership boundary, and its external effects, and sketch the smallest Rust types that express those facts. Stop there, before you compare the sketch with the existing Laravel workflow.

Now compare. The comparison should name a specific operation and a check that can fail when its behavior breaks. Decide which responsibilities stay in Laravel; a focused Rust component can serve one boundary without an application rewrite. Then ask another developer to explain your sketch and run its check, and use what they find to revise any contract that was unclear.

TL;DR

A caller of this code constructs a RunRequest, handles RequestError::EmptyTitle, and passes the valid request to show(). The constructor normalizes and validates, the accessor borrows, and the trait names the one behavior show() needs. From Laravel, borrow names, examples, workflows, and bounded defaults. Judge an interface by what a maintainer must know to make the next likely change. Each check in the series establishes one behavior, and none establishes a whole application. Hold either language to the same standard: named responsibilities, visible effects, and a check that can detect the next likely mistake.

¹ As before, a separate module with private fields is the real API boundary for consumers outside the module. Packaging and visibility are part of finishing a library, not decorative concerns.

The sources.

Every program, its output and every compiler message were recorded on rustc 1.100.0 on 2026-11-20. Each page lists what was not checked.

Rust API Guidelines on naming, predictability, and documentation; Rust Book, traits and ownership; Laravel documentation as a workflow reference. The final interface and cross-language advice are original synthesis.

NOT CHECKED — 4
  • Example 3's PHP output was observed on PHP 8.3.6 when this tutorial was first built; the companion package does not run PHP.
  • The final exercise asks for new work and has no recorded result.
  • The advice on names, examples, workflows and defaults is the series' own synthesis, not a documented claim.
  • The reference links were not opened for this edition.