Traits and dependencies: from PHP interfaces to Rust
Check that a service passes the right ticket ID to its formatter. The regular formatter prepares text for a reader. In the test, substitute an implementation with predictable output.
The formatting contract
trait NotificationFormatterdeclaresformat. It borrows the formatter through&self, takes the ticket ID, and returns aStringowned by the caller.impl NotificationFormatter for TextFormatterimplements that contract for a concrete type. A trait definition can also supply default method implementations.
A PHP interface is the closest analogy here. PHP traits primarily let classes reuse implementation. The chapter on traits explains contracts and generic bounds in Rust.
Choosing a dependency and dispatching calls
- In
NotificationService<F: NotificationFormatter>, the bound requiresFto implement the trait. The concrete type is known at compile time, so the method uses static dispatch. - A reference or smart pointer to
dyn NotificationFormatterallows the method implementation to be selected at runtime. That requires a dyn-compatible trait. See the Rust Reference entry on trait objects. A generic parameter is enough here because the formatter type for each service instance is known at compile time.
main assembles the program. It chooses TextFormatter and passes it to NotificationService::new. The service stores the value and delegates formatting to it. This is explicit constructor injection, familiar from Laravel in PHP. In the test, the same constructor receives TestFormatter.
To see the bound being checked, temporarily replace NotificationService::new(TextFormatter) in main with NotificationService::new(42_u32). The compiler reported E0277 for that substitution because u32 does not implement NotificationFormatter.
Run the program and its test
In the Cargo demo project, replace the entire src/main.rs and run cargo run, then cargo test. The test checks that the substitute formatter receives the supplied ID and separately checks the regular formatter's text.
trait NotificationFormatter {
fn format(&self, ticket_id: u32) -> String;
}
struct TextFormatter;
impl NotificationFormatter for TextFormatter {
fn format(&self, ticket_id: u32) -> String {
format!("Ticket {} updated", ticket_id)
}
}
struct NotificationService<F: NotificationFormatter> {
formatter: F,
}
impl<F: NotificationFormatter> NotificationService<F> {
fn new(formatter: F) -> Self {
Self { formatter }
}
fn message(&self, ticket_id: u32) -> String {
self.formatter.format(ticket_id)
}
}
fn main() {
// The regular implementation is chosen where the program is assembled, outside the service.
let service = NotificationService::new(TextFormatter);
println!("{}", service.message(42));
}
#[cfg(test)]
mod tests {
use super::{NotificationFormatter, NotificationService, TextFormatter};
struct TestFormatter;
impl NotificationFormatter for TestFormatter {
fn format(&self, ticket_id: u32) -> String {
format!("test:{}", ticket_id)
}
}
#[test]
fn delegates_to_injected_formatter() {
// Predictable output lets us check which ID reached the formatter.
let service = NotificationService::new(TestFormatter);
assert_eq!(service.message(7), "test:7");
assert_eq!(service.message(42), "test:42");
let real_service = NotificationService::new(TextFormatter);
assert_eq!(real_service.message(42), "Ticket 42 updated");
}
}
Ticket 42 updated
The example only produces a string. Sending notifications, retrying delivery, and validating input are separate concerns.
Summary
You can test formatting in isolation because the service only needs the formatter's contract. The next block covers routing, validation, and async code in Laravel Rust.