laravel-facade
Laravel-style facades for the shaku DI container. Cache::get("key") in Rust.
Install
Run this in your project folder. cargo add laravel-facade
laravel-facade
Laravel facades for Rust, on top of the shaku DI container.
This is a joke crate. It still follows
Illuminate\Support\Facades\Facade
as closely as Rust allows.
In Laravel, you write this:
use Illuminate\Support\Facades\Cache;
Cache::put('framework', 'Laravel');
Cache::get('framework'); // 'Laravel'
With laravel-facade, you write this:
use std::collections::HashMap;
use std::sync::Mutex;
use laravel_facade::{Application, Facade, extends_facade};
use shaku::{Component, Interface, module};
// class Cache extends Facade
#[extends_facade(Cache)]
pub trait CacheStore: Interface {
fn get(&self, key: &str) -> Option<String>;
fn put(&self, key: &str, value: &str);
}
#[derive(Component)]
#[shaku(interface = CacheStore)]
struct ArrayStore {
#[shaku(default)]
items: Mutex<HashMap<String, String>>,
}
impl CacheStore for ArrayStore {
fn get(&self, key: &str) -> Option<String> {
self.items.lock().unwrap().get(key).cloned()
}
fn put(&self, key: &str, value: &str) {
self.items.lock().unwrap().insert(key.into(), value.into());
}
}
module! {
AppModule {
components = [ArrayStore],
providers = []
}
}
fn main() {
let app = Application::builder(AppModule::builder().build())
.bind::<dyn CacheStore>()
.build();
Facade::set_facade_application(app);
Cache::put("framework", "Laravel");
assert_eq!(Cache::get("framework").as_deref(), Some("Laravel"));
}
Installation
[dependencies]
laravel-facade = "0.1"
shaku = "0.6"
Note
shaku's derive macros expand to ::shaku paths. You need shaku as a direct dependency.
How it works
#[extends_facade(Cache)] keeps the trait as is. It adds these items next to it:
| Generated item | Purpose |
|---|---|
struct Cache; |
The facade. It has the same visibility as the trait. |
impl ExtendsFacade for Cache |
Sets type Accessor = dyn CacheStore. This is getFacadeAccessor(). |
Cache::get(..), Cache::put(..) |
One static method per trait method. This is __callStatic(). |
Cache::swap(..), Cache::fake(..), ... |
The facade API. You do not need to import a trait for it. |
Application is the container behind all facades.
A shaku module cannot be searched by interface at runtime.
So Application must know each interface up front:
| Binding | Use it for | Each resolution returns |
|---|---|---|
bind::<dyn Trait>() |
shaku components | The same shared instance |
bind_provider::<dyn Trait>() |
shaku providers | A new instance |
Note
The TypeId of dyn Trait plays the role of Laravel's string key.
Tip
A facade caches the first instance it resolves, like static::$cached in Laravel.
Use #[extends_facade(Uuid, cached = false)] to get a fresh provider instance on each call.
Generic values, such as Cache::get::<T>()
A facade calls its root through dyn Trait. So the trait cannot have generic methods.
A generic method needs one copy per type, and a vtable cannot hold them all.
Keep the trait type-erased instead. Then add typed entry points to the facade struct.
It is a type of your own crate, so you can write an impl block for it.
use std::any::Any;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use laravel_facade::{Application, Facade, extends_facade};
use shaku::{Component, Interface, module};
type Value = Arc<dyn Any + Send + Sync>;
// The trait stays dyn-compatible: values are type-erased.
#[extends_facade(Cache)]
pub trait CacheStore: Interface {
fn get_value(&self, key: &str) -> Option<Value>;
fn put_value(&self, key: &str, value: Value);
}
// The typed entry points live on the facade struct.
impl Cache {
pub fn get<T: Any + Clone>(key: &str) -> Option<T> {
Cache::get_value(key)?.downcast_ref::<T>().cloned()
}
pub fn put<T: Any + Send + Sync>(key: &str, value: T) {
Cache::put_value(key, Arc::new(value));
}
}
#[derive(Component)]
#[shaku(interface = CacheStore)]
struct ArrayStore {
#[shaku(default)]
items: Mutex<HashMap<String, Value>>,
}
impl CacheStore for ArrayStore {
fn get_value(&self, key: &str) -> Option<Value> {
self.items.lock().unwrap().get(key).cloned()
}
fn put_value(&self, key: &str, value: Value) {
self.items.lock().unwrap().insert(key.into(), value);
}
}
module! {
AppModule {
components = [ArrayStore],
providers = []
}
}
#[derive(Clone, Debug, PartialEq)]
struct User {
name: String,
}
fn main() {
let app = Application::builder(AppModule::builder().build())
.bind::<dyn CacheStore>()
.build();
Facade::set_facade_application(app);
Cache::put("count", 42_u32);
Cache::put("user", User { name: "Taylor".into() });
assert_eq!(Cache::get::<u32>("count"), Some(42));
assert_eq!(Cache::get::<User>("user"), Some(User { name: "Taylor".into() }));
// A value of another type is a miss, not a panic.
assert_eq!(Cache::get::<String>("count"), None);
}
The trait is still dyn-compatible. So swap(), fake(), and #[automock] work as before.
Pick how to erase the value by where the store keeps it:
| Store | Erase the value as | Bound on T |
|---|---|---|
In the process, like Laravel's array driver |
Arc<dyn Any + Send + Sync> |
T: Any + Clone |
| Outside the process, like Redis | Bytes, through serde | T: Serialize + DeserializeOwned |
Testing
A swapped instance wins over the application. You do not even need an application in tests.
use std::sync::Mutex;
use laravel_facade::{Facade, Fake, extends_facade};
use mockall::automock;
use mockall::predicate::eq;
use shaku::Interface;
#[extends_facade(Mail)]
#[automock]
pub trait Mailer: Interface {
fn send(&self, to: &str, body: &str) -> bool;
}
fn send_welcome(to: &str) -> bool {
Mail::send(to, "Welcome!")
}
#[derive(Default)]
struct MailFake {
sent: Mutex<Vec<String>>,
}
impl Fake for MailFake {}
impl Mailer for MailFake {
fn send(&self, to: &str, _body: &str) -> bool {
self.sent.lock().unwrap().push(to.into());
true
}
}
fn main() {
// Mail::fake()
let fake = Mail::fake(MailFake::default());
assert!(send_welcome("[email protected]"));
assert!(Mail::is_fake());
assert_eq!(*fake.sent.lock().unwrap(), ["[email protected]"]);
// Mail::shouldReceive('send')->with(...)->once()->andReturn(false)
Mail::should_receive(|mock: &mut MockMailer| {
mock.expect_send()
.with(eq("[email protected]"), eq("Welcome!"))
.times(1)
.return_const(false);
});
assert!(!send_welcome("[email protected]"));
// Mockery::close(): drops the mock, and mockall checks `times(1)`.
Facade::clear_resolved_instances();
}
| Method | Swaps in | is_fake() |
|---|---|---|
Mail::swap(Arc<dyn Mailer>) |
Any instance | false |
Mail::fake(T) |
A T: Mailer + Fake. It returns Arc<T> for assertions. |
true |
Mail::should_receive(|m: &mut M| ...) |
M::default(), such as a mockall mock |
false |
Tip
Like Laravel, a second should_receive() with the same mock type adds to the same mock.
expects() is an alias.
Warning
Facade state is global, as in Laravel. But Rust runs the tests of one binary in parallel threads. Use serial_test for tests that touch facades. Reset the state at the end of each test:
use laravel_facade::Facade;
Facade::clear_resolved_instances();
Facade::set_facade_application(None);
Laravel mapping
Each row shows the same thing in Laravel and in laravel-facade.
| What | Laravel | laravel-facade |
|---|---|---|
Define a facade. The trait is the accessor. The macro writes impl ExtendsFacade for Cache with type Accessor = dyn CacheStore. |
|
|
| Do not cache the resolved instance. Each call resolves the accessor again. |
|
|
Call the root through the facade. Laravel forwards with __callStatic() at runtime. The macro generates one static method per trait method. |
|
|
| Bind the accessors in the container. A shaku component is shared. A shaku provider builds a new instance each time. |
|
|
| Set the application behind all facades. Laravel does it while booting. Here you call it yourself. |
|
|
Get the root instance. Without an application, it panics with A facade root has not been set. The try_ version returns an Error instead. |
|
|
| Hot-swap the root. It also replaces the instance in the application. |
|
|
Swap in a fake. A type marked with Fake makes is_fake() return true. fake() returns the fake for assertions. |
|
|
Set expectations on a mock. The first call swaps in MockCacheStore::default(). Later calls add to the same mock. |
|
|
Same as shouldReceive(), with the other name. |
|
|
| Run a callback when the root is resolved. If it was already resolved, the callback runs right away too. |
|
|
| Clear cached roots. Laravel names the accessor with a string. Here the facade or the accessor type names it. |
|
|
| Spies and partial mocks. mockall has neither, so they are not supported. |
|
Not supported |
Short names for facades. Laravel registers aliases. Rust has use. |
|
|
What the macro can forward
The macro looks at each trait method. It forwards it, skips it, or stops with a compile error.
| Trait method | Example | Result | Static method or error |
|---|---|---|---|
A &self method |
|
Forwarded |
|
A self: Arc<Self> method. The facade passes its root Arc. |
|
Forwarded |
|
| A method that returns a borrow of an argument, with a named lifetime |
|
Forwarded |
|
An async fn under #[async_trait], with #[extends_facade] above it |
|
Forwarded |
|
A method with where Self: Sized. It is not callable on dyn Trait, so there is nothing to forward to. |
|
Skipped | No static method |
A method that returns a borrow of self. The borrow would outlive the root Arc. |
|
Compile error |
|
A &mut self method. The root is shared. |
|
Compile error |
|
A self method without where Self: Sized |
|
Compile error |
|
Any other receiver, such as Box<Self> |
|
Compile error |
|
| A method named like a generated one |
|
Compile error |
|
| A generic trait |
|
Compile error |
|
#[extends_facade] below #[async_trait]. It would see the rewritten methods. |
|
Compile error |
|
License
MIT