Skip to main content

rustlavel_http/
plugin.rs

1//! How an optional package attaches itself to an application.
2//!
3//! Laravel discovers packages at runtime and boots them by reflection. Here a
4//! package is enabled by one explicit line in `main.rs`:
5//!
6//! ```ignore
7//! App::new().plugin(Telescope::default())
8//! ```
9//!
10//! The trait lives in the HTTP crate rather than the meta-crate so a package
11//! can implement it without depending on `rustlavel` itself — which would
12//! otherwise be a dependency cycle.
13
14use crate::router::Router;
15use rustlavel_core::{Config, ContextBuilder};
16
17/// What a plugin is handed when it registers.
18pub struct Setup<'a> {
19    pub router: &'a mut Router,
20    pub config: &'a Config,
21    pub context: &'a mut Option<ContextBuilder>,
22}
23
24impl Setup<'_> {
25    /// Register a service the plugin's own handlers will resolve later.
26    pub fn state<T: Send + Sync + 'static>(&mut self, value: T) {
27        let builder = self.context.take().expect("context builder is available during setup");
28        *self.context = Some(builder.state(value));
29    }
30}
31
32pub trait Plugin: Send + 'static {
33    /// Shown by `rustlavel route:list` and in boot logs.
34    fn name(&self) -> &'static str;
35
36    /// Add routes, middleware, and state.
37    fn register(self: Box<Self>, setup: &mut Setup<'_>);
38}