Skip to main content

Crate laravel_facade

Crate laravel_facade 

Source
Expand description

laravel-facade logo

laravel-facade

CI codecov crates.io docs.rs

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 itemPurpose
struct Cache;The facade. It has the same visibility as the trait.
impl ExtendsFacade for CacheSets 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:

BindingUse it forEach resolution returns
bind::<dyn Trait>()shaku componentsThe same shared instance
bind_provider::<dyn Trait>()shaku providersA 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:

StoreErase the value asBound on T
In the process, like Laravel’s array driverArc<dyn Any + Send + Sync>T: Any + Clone
Outside the process, like RedisBytes, through serdeT: 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();
}
MethodSwaps inis_fake()
Mail::swap(Arc<dyn Mailer>)Any instancefalse
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 mockfalse

[!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.

WhatLaravellaravel-facade
Define a facade. The trait is the accessor. The macro writes impl ExtendsFacade for Cache with type Accessor = dyn CacheStore.
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);
}
Do not cache the resolved instance. Each call resolves the accessor again.
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;
}
Call the root through the facade. Laravel forwards with __callStatic() at runtime. The macro generates one static method per trait method.
Cache::put('framework', 'Laravel');

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

let value = Cache::get("framework");
Bind the accessors in the container. A shaku component is shared. A shaku provider builds a new instance each time.
$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();
Set the application behind all facades. Laravel does it while booting. Here you call it yourself.
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);
Get the root instance. Without an application, it panics with A facade root has not been set. The try_ version returns an Error instead.
$store = Cache::getFacadeRoot();
let store: Arc<dyn CacheStore> = Cache::get_facade_root();

let store = Cache::try_get_facade_root()?;
Hot-swap the root. It also replaces the instance in the application.
Cache::swap(new ArrayStore);
Cache::swap(Arc::new(ArrayStore::default()));
Swap in a fake. A type marked with Fake makes is_fake() return true. fake() returns the fake for assertions.
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
Set expectations on a mock. The first call swaps in MockCacheStore::default(). Later calls add to the same mock.
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()));
});
Same as shouldReceive(), with the other name.
Cache::expects('get')
    ->andReturn('value');
Cache::expects(|mock: &mut MockCacheStore| {
    mock.expect_get()
        .return_const(Some("value".to_owned()));
});
Run a callback when the root is resolved. If it was already resolved, the callback runs right away too.
Cache::resolved(function ($cache, $app) {
    // ...
});
Cache::resolved(|cache, app| {
    // ...
});
Clear cached roots. Laravel names the accessor with a string. Here the facade or the accessor type names it.
Cache::clearResolvedInstance('cache');

Facade::clearResolvedInstance('cache');

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

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

Facade::clear_resolved_instances();
Spies and partial mocks. mockall has neither, so they are not supported.
Cache::spy();

Cache::partialMock();
Not supported
Short names for facades. Laravel registers aliases. Rust has use.
// 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.

Trait methodExampleResultStatic method or error
A &self method
fn get(&self, key: &str) -> Option<String>;
Forwarded
pub fn get(key: &str) -> Option<String>
A self: Arc<Self> method. The facade passes its root Arc.
fn shared(self: Arc<Self>) -> usize;
Forwarded
pub fn shared() -> usize
A method that returns a borrow of an argument, with a named lifetime
fn first<'a>(&self, keys: &'a [String]) -> &'a str;
Forwarded
pub fn first<'a>(keys: &'a [String]) -> &'a str
An async fn under #[async_trait], with #[extends_facade] above it
#[extends_facade(Http)]
#[async_trait]
pub trait HttpClient: Interface {
    async fn get(&self, url: &str) -> String;
}
Forwarded
pub async fn get(url: &str) -> String
A method with where Self: Sized. It is not callable on dyn Trait, so there is nothing to forward to.
fn new() -> Self
where
    Self: Sized;
Skipped No static method
A method that returns a borrow of self. The borrow would outlive the root Arc.
fn name(&self) -> &str;
Compile error
#[extends_facade] cannot forward a method that returns
a borrow of `self`; return an owned value or name the
lifetime of an argument
A &mut self method. The root is shared.
fn increment(&mut self);
Compile error
#[extends_facade] cannot forward `&mut self` methods:
the facade root is shared behind `Arc`
A self method without where Self: Sized
fn into_inner(self) -> String;
Compile error
#[extends_facade] cannot forward `self` methods;
add `where Self: Sized` to skip it
Any other receiver, such as Box<Self>
fn boxed(self: Box<Self>);
Compile error
#[extends_facade] can only forward `&self` and
`self: Arc<Self>` methods
A method named like a generated one
fn swap(&self);
Compile error
`swap` clashes with a method generated on every facade
A generic trait
#[extends_facade(Repo)]
pub trait Repository<T>: Interface {
    fn find(&self, id: u64) -> Option<T>;
}
Compile error
#[extends_facade] does not support generic traits
#[extends_facade] below #[async_trait]. It would see the rewritten methods.
#[async_trait]
#[extends_facade(Http)]
pub trait HttpClient: Interface {
    async fn get(&self, url: &str) -> String;
}
Compile error
#[extends_facade] must be placed above #[async_trait]

§License

MIT

Re-exports§

pub use shaku;

Structs§

Application
The container behind facades.
ApplicationBuilder
Builder returned by Application::builder.

Enums§

Error
Errors raised while resolving a facade root.
Facade
The base of all facades. Same as Illuminate\Support\Facades\Facade.

Traits§

ExtendsFacade
A facade: a static proxy to a shaku interface. Same as class Cache extends Facade.
Fake
Marker for test doubles. Same as Illuminate\Support\Testing\Fakes\Fake.

Attribute Macros§

extends_facade
Turns a shaku interface trait into a Laravel-style facade.