laravel-facade 0.1.3

Laravel-style facades for the shaku DI container. Cache::get("key") in Rust.
Documentation

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.

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("taylor@example.com"));
    assert!(Mail::is_fake());
    assert_eq!(*fake.sent.lock().unwrap(), ["taylor@example.com"]);

    // Mail::shouldReceive('send')->with(...)->once()->andReturn(false)
    Mail::should_receive(|mock: &mut MockMailer| {
        mock.expect_send()
            .with(eq("taylor@example.com"), eq("Welcome!"))
            .times(1)
            .return_const(false);
    });
    assert!(!send_welcome("taylor@example.com"));

    // 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.

class Cache extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'cache';
    }
}
#[extends_facade(Cache)]
pub trait CacheStore: Interface {
    fn get(&self, key: &str) -> Option<String>;
    fn put(&self, key: &str, value: &str);
}
class Uuid extends Facade
{
    protected static $cached = false;

    protected static function getFacadeAccessor()
    {
        return 'uuid';
    }
}
#[extends_facade(Uuid, cached = false)]
pub trait IdGenerator: Interface {
    fn id(&self) -> usize;
}
Cache::put('framework', 'Laravel');

$value = Cache::get('framework');
Cache::put("framework", "Laravel");

let value = Cache::get("framework");
$app->singleton('cache', fn () => new ArrayStore);

$app->bind('uuid', fn () => new UuidGenerator);
let app = Application::builder(AppModule::builder().build())
    .bind::<dyn CacheStore>()
    .bind_provider::<dyn IdGenerator>()
    .build();
Facade::setFacadeApplication($app);

$app = Facade::getFacadeApplication();

Facade::setFacadeApplication(null);
Facade::set_facade_application(app);

let app = Facade::get_facade_application();

Facade::set_facade_application(None);
$store = Cache::getFacadeRoot();
let store: Arc<dyn CacheStore> = Cache::get_facade_root();

let store = Cache::try_get_facade_root()?;
Cache::swap(new ArrayStore);
Cache::swap(Arc::new(ArrayStore::default()));
class CacheFake implements Fake
{
    // ...
}

Cache::swap(new CacheFake);

Cache::isFake(); // true
impl Fake for CacheFake {}

let fake = Cache::fake(CacheFake::default());

Cache::is_fake(); // true
Cache::shouldReceive('get')
    ->with('key')
    ->once()
    ->andReturn('value');
Cache::should_receive(|mock: &mut MockCacheStore| {
    mock.expect_get()
        .with(eq("key"))
        .times(1)
        .return_const(Some("value".to_owned()));
});
Cache::expects('get')
    ->andReturn('value');
Cache::expects(|mock: &mut MockCacheStore| {
    mock.expect_get()
        .return_const(Some("value".to_owned()));
});
Cache::resolved(function ($cache, $app) {
    // ...
});
Cache::resolved(|cache, app| {
    // ...
});
Cache::clearResolvedInstance('cache');

Facade::clearResolvedInstance('cache');

Facade::clearResolvedInstances();
Cache::clear_resolved_instance();

Facade::clear_resolved_instance::<dyn CacheStore>();

Facade::clear_resolved_instances();
Cache::spy();

Cache::partialMock();
// config/app.php
'aliases' => Facade::defaultAliases()->merge([
    'Cache' => Illuminate\Support\Facades\Cache::class,
])->toArray(),
use crate::facades::Cache;

What the macro can forward

The macro looks at each trait method. It forwards it, skips it, or stops with a compile error.

fn get(&self, key: &str) -> Option<String>;
pub fn get(key: &str) -> Option<String>
fn shared(self: Arc<Self>) -> usize;
pub fn shared() -> usize
fn first<'a>(&self, keys: &'a [String]) -> &'a str;
pub fn first<'a>(keys: &'a [String]) -> &'a str
#[extends_facade(Http)]
#[async_trait]
pub trait HttpClient: Interface {
    async fn get(&self, url: &str) -> String;
}
pub async fn get(url: &str) -> String
fn new() -> Self
where
    Self: Sized;
fn name(&self) -> &str;
#[extends_facade] cannot forward a method that returns
a borrow of `self`; return an owned value or name the
lifetime of an argument
fn increment(&mut self);
#[extends_facade] cannot forward `&mut self` methods:
the facade root is shared behind `Arc`
fn into_inner(self) -> String;
#[extends_facade] cannot forward `self` methods;
add `where Self: Sized` to skip it
fn boxed(self: Box<Self>);
#[extends_facade] can only forward `&self` and
`self: Arc<Self>` methods
fn swap(&self);
`swap` clashes with a method generated on every facade
#[extends_facade(Repo)]
pub trait Repository<T>: Interface {
    fn find(&self, id: u64) -> Option<T>;
}
#[extends_facade] does not support generic traits
#[async_trait]
#[extends_facade(Http)]
pub trait HttpClient: Interface {
    async fn get(&self, url: &str) -> String;
}
#[extends_facade] must be placed above #[async_trait]

License

MIT