laravel-rust 0.1.3

Laravel for Rust: a full-stack Rust web framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# Service Container

- [Introduction](#introduction)
- [Registering services](#registering-services)
    - [Registering services in `src/app.rs`](#registering-services-in-app)
    - [Building a fresh service each time](#building-a-fresh-service-each-time)
    - [Depending on other services](#depending-on-other-services)
    - [Trait contracts](#trait-contracts)
    - [Replacing a service](#replacing-a-service)
    - [Registering services with attributes](#service-functions)
- [Using services](#using-services)
    - [In handlers](#in-handlers)
    - [Anywhere else](#anywhere-else)
    - [When the application boots](#when-the-application-boots)
- [Singletons and shared state](#services-are-shared)

<a name="introduction"></a>
## Introduction

Most applications have values they build once and use everywhere: a client for your payment provider, a calculator that knows your tax rates, or a cache of settings loaded from the database. Building one in every handler is wasteful, and passing it through every function is tedious. The service container holds values like these. You register a service once, Laravel builds it the first time something needs it, and every handler that asks for it by type gets the same instance.

Many Rust frameworks keep shared values in a single application state struct, such as Axum's `State`, which every handler receives whole. Laravel registers each service on its own instead. A handler asks for just the services it uses, such as `Inject<Stripe>`, and a service that nothing asks for is never built.

A handler that takes `Inject<Stripe>` doesn't need to know where the API key comes from or how the client is built. And in tests, you may [swap the service](testing.md#swapping-services) for a fake without changing the handler.

Laravel registers its own services, such as the database, the cache, and the mailer, and you reach them through helpers such as `laravel::mail::to(..)`. You'll use the container for the services your application adds.

Reserve the container for types that hold configuration, external clients, shared state, or a [trait contract](#trait-contracts) you want to swap in tests. Stateless domain logic, such as placing an order or building an export, doesn't need an empty struct registered as a singleton. Write plain `pub async fn` functions in a module such as `src/orders.rs` instead, and call your models, helpers such as `laravel::mail::to(..)`, or [`laravel::resolve`](#anywhere-else) directly from them.

<a name="registering-services"></a>
## Registering services

Say your application charges cards through Stripe. The client needs your Stripe key, which a [configuration section](configuration.md#your-own-config-sections) reads from the environment. This file defines the client and its configuration section:

```rust
// src/services/stripe.rs
use laravel::config::Section;
use laravel::http::client;

#[derive(Clone, Section)]
pub struct StripeConfig {
    #[env("STRIPE_KEY", required)]
    pub key: String,
}

pub struct Stripe {
    key: String,
}

impl Stripe {
    pub fn new(key: &str) -> Self {
        Self { key: key.to_owned() }
    }

    pub async fn charge(&self, cents: u64) -> laravel::Result<()> {
        client::post("https://api.stripe.com/v1/payment_intents")
            .token(&self.key)
            .form([("amount", cents.to_string()), ("currency", "usd".to_owned())])
            .await?;

        Ok(())
    }
}
```

<a name="registering-services-in-app"></a>
### Registering services in `src/app.rs`

Register the service in `src/app.rs` with `with_services`. `singleton` registers an async factory that runs the first time something asks for the service:

```rust
// src/app.rs
use laravel::Application;
use laravel::foundation::ApplicationBuilder;

use crate::services::stripe::{Stripe, StripeConfig};

pub fn configure() -> ApplicationBuilder {
    Application::configure().with_services(|app| {
        app.singleton(async |app| {
            let key = &app.config().section::<StripeConfig>().key;

            Ok(Stripe::new(key))
        });
    })
}
```

Any handler can now take an `Inject<Stripe>`. The factory receives the container, so it may read your configuration with `app.config()`. It returns a `laravel::Result`, so you may use `?`. If it fails, the code that asked gets the error, and the next request tries again.

When a service needs nothing from your configuration or other services, you may build it yourself and register the finished value with `instance`. This `Pricing` calculator only needs your tax rate:

```rust
// src/app.rs
use crate::services::pricing::Pricing;

app.instance(Pricing::new(0.07));
```

Handlers then take `Inject<Pricing>`, the same as for a service built by a factory. To build a new service every time something asks for it, use `bind`, as [Building a fresh service each time](#building-a-fresh-service-each-time) describes.

> [!NOTE]
> Register the service itself, such as `Stripe`, rather than an `Arc<Stripe>`. The container already shares one instance, and `Inject<Stripe>` looks for it under `Stripe`. Keep `Arc<T>` for the fields of services that [depend on other services](#depending-on-other-services).

<a name="building-a-fresh-service-each-time"></a>
### Building a fresh service each time

`singleton` builds one service and shares it with every request, which suits a payment client or anything else that works the same for every request. When a service needs something from the current request, such as the tenant or the logged-in user, register it with `bind` instead. Its factory runs every time something asks for the service, inside the request that asks, so it may read that request's [context values](context.md#adding-to-the-context). This `TenantReports` service is built for the tenant the current request belongs to:

```rust
// src/app.rs
use laravel::context;

use crate::services::reports::TenantReports;

app.bind(async |_app| {
    let tenant: Option<String> = context::get("tenant");

    Ok(TenantReports::new(tenant))
});
```

For a [trait contract](#trait-contracts), use `bind_as`. To register a fresh-each-time service next to its code instead of in `src/app.rs`, use the [`#[bind]` attribute](#service-functions).

<a name="depending-on-other-services"></a>
### Depending on other services

Services often need other services. A checkout, for example, needs Stripe to take payments. Keep the other service in an `Arc<T>` field:

```rust
// src/services/checkout.rs
use std::sync::Arc;

use crate::services::stripe::Stripe;

pub struct Checkout {
    stripe: Arc<Stripe>,
}

impl Checkout {
    pub fn new(stripe: Arc<Stripe>) -> Self {
        Self { stripe }
    }

    pub async fn pay(&self, cents: u64) -> laravel::Result<()> {
        self.stripe.charge(cents).await
    }
}
```

In the factory, resolve the other service from the container. `resolve` returns it as an `Arc<T>`, ready to keep in a field:

```rust
// src/app.rs
app.singleton(async |app| {
    let stripe = app.resolve::<Stripe>().await?;

    Ok(Checkout::new(stripe))
});
```

`Checkout` shares the same `Stripe` as every handler that takes `Inject<Stripe>`.

<a name="trait-contracts"></a>
### Trait contracts

Sometimes you'd like code to use a service without naming its implementation. Say your application looks up addresses through a geocoder. It uses Mapbox today, but you might move to Google Maps later. Register the geocoder under a trait contract, and your handlers ask for `Inject<dyn Geocoder>`. Switching to Google Maps then changes one registration and no handlers.

Rust can't call `async fn` trait methods through `dyn Trait`, so add the `async-trait` crate to your `Cargo.toml` and put `#[async_trait]` on the trait and on each implementation:

```toml
[dependencies]
async-trait = "0.1"
```

Define the contract:

```rust
// src/services/geocoder.rs
use async_trait::async_trait;

pub struct Coordinates {
    pub latitude: f64,
    pub longitude: f64,
}

#[async_trait]
pub trait Geocoder: Send + Sync {
    async fn locate(&self, address: &str) -> laravel::Result<Coordinates>;
}
```

Then implement it for Mapbox:

```rust
// src/services/mapbox.rs
use async_trait::async_trait;
use laravel::config::Section;

use crate::services::geocoder::{Coordinates, Geocoder};

#[derive(Clone, Section)]
pub struct MapboxConfig {
    #[env("MAPBOX_TOKEN", required)]
    pub token: String,
}

pub struct Mapbox {
    token: String,
}

impl Mapbox {
    pub fn new(token: &str) -> Self {
        Self { token: token.to_owned() }
    }
}

#[async_trait]
impl Geocoder for Mapbox {
    async fn locate(&self, address: &str) -> laravel::Result<Coordinates> {
        // Fetch the address's coordinates from Mapbox's API...
    }
}
```

Register it with `singleton_as`, whose factory returns the service as an `Arc<dyn Geocoder>`:

```rust
// src/app.rs
use std::sync::Arc;

use crate::services::geocoder::Geocoder;
use crate::services::mapbox::{Mapbox, MapboxConfig};

app.singleton_as(async |app| {
    let token = &app.config().section::<MapboxConfig>().token;

    Ok(Arc::new(Mapbox::new(token)) as Arc<dyn Geocoder>)
});
```

Now your handlers can ask for the contract instead of Mapbox itself. This one looks up an address without knowing which service answers:

```rust
use laravel::prelude::*;

use crate::services::geocoder::Geocoder;

pub async fn show(geocoder: Inject<dyn Geocoder>) -> laravel::Result<String> {
    let place = geocoder.locate("1600 Pennsylvania Ave NW, Washington, DC").await?;

    Ok(format!("{}, {}", place.latitude, place.longitude))
}
```

To move to Google Maps, implement `Geocoder` for a `GoogleMaps` service and change the registration. The handlers stay as they are. If you also register `Mapbox` itself, register the contract separately: the container never binds a struct's traits on its own. For a value you've already built, use `instance_as`.

Contracts make your tests simpler too. In a test, you may swap in a fake geocoder that returns fixed coordinates, so your tests never call Mapbox, and Mapbox needs no test-only code of its own. The testing guide's [swapping services](testing.md#swapping-services) section shows how, with `swap_as`.

<a name="replacing-a-service"></a>
### Replacing a service

Registering the same type again replaces the earlier registration. Your application's services register after every package's, so you may replace a package's service, such as a `Stripe` client from a billing package, with your own:

```rust
// src/app.rs
Application::configure().with_services(|app| {
    app.instance(Stripe::new("sk_test_..."));
})
```

<a name="service-functions"></a>
### Registering services with attributes

Each service you register in `src/app.rs` adds another factory to that file, so it can get long. The `#[singleton]` and `#[bind]` attributes let you register a service next to its code instead. Mark an async function with `#[singleton]`, and it becomes the factory for the service it returns. The function takes what the service needs as arguments, the same way a handler does: configuration sections as `Section<T>`, and other services as `Inject<T>`.

This function registers the same `Stripe` service, from `src/services/stripe.rs`:

```rust
// src/services/stripe.rs
use laravel::container::singleton;

#[singleton]
async fn stripe(config: Section<StripeConfig>) -> laravel::Result<Stripe> {
    Ok(Stripe::new(&config.key))
}
```

To [build a fresh service each time](#building-a-fresh-service-each-time) something asks for it, use `#[bind]` instead:

```rust
// src/services/reports.rs
use laravel::container::bind;

#[bind]
async fn tenant_reports() -> laravel::Result<TenantReports> {
    Ok(TenantReports::new(laravel::context::get("tenant")))
}
```

Laravel finds these services on its own, so you don't register them in `src/app.rs`. They may live in any module, as long as the module is declared, such as with `pub mod services;` in `src/lib.rs`. Rust only compiles declared modules, so Laravel never sees a service in a file you haven't declared.

To register the service under a [trait contract](#trait-contracts) too, name the contract with `as`. This function registers the Mapbox geocoder from that section, in place of its `singleton_as` call in `src/app.rs`:

```rust
// src/services/mapbox.rs
use laravel::container::singleton;

#[singleton(as = dyn Geocoder)]
async fn mapbox(config: Section<MapboxConfig>) -> laravel::Result<Mapbox> {
    Ok(Mapbox::new(&config.token))
}
```

Handlers that take `Inject<dyn Geocoder>` and handlers that take `Inject<Mapbox>` now share the same instance.

<a name="using-services"></a>
## Using services

<a name="in-handlers"></a>
### In handlers

Handlers take an `Inject<T>` argument, which dereferences to the service:

```rust
use laravel::prelude::*;

use crate::services::stripe::Stripe;

pub async fn store(stripe: Inject<Stripe>) -> laravel::Result<Redirect> {
    stripe.charge(2_000).await?;

    Ok(Redirect::back())
}
```

[Middleware functions](middleware.md#middleware-arguments), [jobs](queues.md), [listeners](events.md), and [console commands](console.md) take services as `Inject<T>` arguments the same way.

<a name="anywhere-else"></a>
### Anywhere else

Code without handler arguments, such as a scheduled task or the closure given to [`once`](context.md#memoizing-with-once), can call `laravel::resolve`. Resolving may build the service, so `.await` it:

```rust
use crate::services::stripe::Stripe;

pub async fn charge_monthly_fee() -> laravel::Result<()> {
    let stripe = laravel::resolve::<Stripe>().await?;

    stripe.charge(1_000).await
}
```

`laravel::resolve` works anywhere your application runs: in requests, commands, jobs, boot hooks, and tests.

<a name="when-the-application-boots"></a>
### When the application boots

Laravel builds each service the first time something uses it, not when the application boots. If a factory fails, such as when its server is down, the first request that needs the service fails. To build a service at boot instead, resolve it in a `booted` callback in `src/app.rs`. The callback runs once, after every package's provider boots, and an error from it stops the application from booting:

```rust
// src/app.rs
use laravel::Application;

use crate::services::stripe::Stripe;

Application::configure().booted(async |app| {
    app.resolve::<Stripe>().await?;

    Ok(())
})
```

<a name="services-are-shared"></a>
## Singletons and shared state

A singleton serves every request for as long as your application runs, and `Inject<T>` gives each request a shared reference to it, as an `Arc` would. So a service's fields hold what every request shares, never anything about one request. Pass the current user and other per-request values to its methods instead:

```rust
// src/services/checkout.rs
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use crate::models::User;
use crate::services::stripe::Stripe;

pub struct Checkout {
    stripe: Arc<Stripe>,
    orders: AtomicU64,
}

impl Checkout {
    pub fn new(stripe: Arc<Stripe>) -> Self {
        Self { stripe, orders: AtomicU64::new(0) }
    }

    pub async fn pay(&self, user: &User, cents: u64) -> laravel::Result<()> {
        self.stripe.charge(cents).await?;
        self.orders.fetch_add(1, Ordering::Relaxed);

        tracing::info!(user.id = user.id, cents, "Checkout complete");

        Ok(())
    }
}
```

The handler passes in the logged-in user, so two customers checking out at the same moment never see each other's details:

```rust
use laravel::prelude::*;

use crate::models::User;
use crate::services::checkout::Checkout;

pub async fn store(
    user: Authenticated<User>,
    checkout: Inject<Checkout>,
) -> laravel::Result<Redirect> {
    checkout.pay(&user, 2_000).await?;

    Ok(Redirect::back())
}
```

`orders` counts every order the service takes, across all requests. `pay` only has `&self`, so the count is an `AtomicU64`, which it can update through a shared reference. For other data a service changes as it runs, use a `Mutex`, as you would for any value shared between threads.

> [!NOTE]
> A handler that holds a standard `Mutex` lock across an `.await` doesn't compile, and the error points at its route: "this function can't handle requests". Add [`#[laravel::routing::debug_handler]`](handlers.md#when-a-function-cant-handle-requests) to the handler, and the compiler names the lock. Release the lock before the `.await`, or use `tokio::sync::Mutex` if you need to hold it.