LaraflareDocsPackages13.x

Docs / Architecture Concepts / Facades

Facades

Introduction

Throughout the Laraflare documentation, you will see examples of code that interacts with Laraflare's features via "facades". Facades provide a "static" interface to classes that are available in the application's service container. Laraflare ships with many facades which provide access to almost all of Laraflare's features.

Laraflare facades serve as "static proxies" to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods. It's perfectly fine if you don't totally understand how facades work - just go with the flow and continue learning about Laraflare.

All of Laraflare's facades are exported from the @laraflare/framework package. So, we can easily access a facade like so:

import { Cache, Route } from '@laraflare/framework';

Route.get('/cache', async () => {
  return await Cache.get('key');
});

Throughout the Laraflare documentation, many of the examples will use facades to demonstrate various features of the framework.

Helper Functions

To complement facades, Laraflare offers a variety of global "helper functions" that make it even easier to interact with common Laraflare features. Some of the common helper functions you may interact with are view, response, url, config, and more. Each helper function offered by Laraflare is documented with their corresponding feature.

For example, instead of using the Response facade to generate a JSON response, we may simply use the response function:

import { Route, response } from '@laraflare/framework';

Route.get('/users', () => {
  return response().json({
    // ...
  });
});

When to Utilize Facades

Facades have many benefits. They provide a terse, memorable syntax that allows you to use Laraflare's features without remembering long class names that must be injected or configured manually. Furthermore, because of their unique usage of dynamic method proxying, they are easy to test.

However, some care must be taken when using facades. The primary danger of facades is class "scope creep". Since facades are so easy to use and do not require injection, it can be easy to let your classes continue to grow and use many facades in a single class. Using dependency injection, this potential is mitigated by the visual feedback a large constructor gives you that your class is growing too large. So, when using facades, pay special attention to the size of your class so that its scope of responsibility stays narrow. If your class is getting too large, consider splitting it into multiple smaller classes.

Facades vs. Dependency Injection

One of the primary benefits of dependency injection is the ability to swap implementations of the injected class. This is useful during testing since you can inject a mock or stub and assert that various methods were called on the stub.

Typically, it would not be possible to mock or stub a truly static class method. However, since facades proxy method calls to objects resolved from the service container, we actually can test facades just as we would test an injected class instance. For example, given the following route:

import { Cache, Route } from '@laraflare/framework';

Route.get('/cache', async () => {
  return await Cache.get('key');
});

Using Laraflare's facade testing methods, we can write the following test to verify that the Cache.get method was called with the argument we expected:

import { Cache } from '@laraflare/framework';
import { test } from '../Pest';

test('basic example', async function () {
  Cache.shouldReceive('get')
    .with('key')
    .andReturn('value');

  const response = await this.get('/cache');

  response.assertSee('value');
});

Facades vs. Helper Functions

In addition to facades, Laraflare includes a variety of "helper" functions which can perform common tasks like generating views, firing events, dispatching jobs, or sending HTTP responses. Many of these helper functions perform the same function as a corresponding facade. For example, this facade call and helper call are equivalent:

return View.make('profile');

return view('profile');

There is absolutely no practical difference between facades and helper functions. When using helper functions, you may still test them exactly as you would the corresponding facade. For example, given the following route:

Route.get('/cache', async () => {
  return await cache('key');
});

The cache helper is going to call the get method on the class underlying the Cache facade. So, even though we are using the helper function, we can write the following test to verify that the method was called with the argument we expected:

import { Cache } from '@laraflare/framework';
import { test } from '../Pest';

test('basic example', async function () {
  Cache.shouldReceive('get')
    .with('key')
    .andReturn('value');

  const response = await this.get('/cache');

  response.assertSee('value');
});

How Facades Work

In a Laraflare application, a facade is a class that provides access to an object from the container. The machinery that makes this work is in the Facade class. Laraflare's facades, and any custom facades you create, extend the base Facade class.

The Facade base class defers calls from your facade to an object resolved from the container. In the example below, a call is made to the Laraflare cache system. By glancing at this code, one might assume that the static get method is being called on the Cache class:

import { Cache } from '@laraflare/framework';

export class UserController {
  /**
   * Show the profile for the given user.
   */
  async showProfile(id: string) {
    const user = await Cache.get('user:' + id);

    return view('profile', { user });
  }
}

Notice that near the top of the file we are "importing" the Cache facade. This facade serves as a proxy for accessing the underlying implementation of the cache service. Any calls we make using the facade will be passed to the underlying instance of Laraflare's cache service.

If we look at the Cache facade's class, you'll see that there is no static method get:

class CacheFacade extends Facade {
  /**
   * Get the registered name of the component.
   */
  protected static override getFacadeAccessor(): string {
    return 'cache';
  }
}

export const Cache = facade<typeof CacheFacade, CacheManager & Repository>(CacheFacade);

Instead, the Cache facade extends the base Facade class and defines the method getFacadeAccessor(). This method's job is to return the name of a service container binding. The facade() function wraps the class so that a reference to any other static method on the Cache facade resolves the cache binding from the service container and runs the requested method (in this case, get) against that object.

Note

Laraflare has no real-time facades: a class cannot be used as a facade just by prefixing its import. To use a class of your own as a facade, extend Facade and wrap it with facade() as above, or bind it in the service container and inject it.

Facade Class Reference

Below you will find the facades Laraflare ships and the service container binding key each one resolves, where it has one. Every facade can be mocked in tests with shouldReceive, expects, spy and partialMock.

Facade Service Container Binding
App app
Artisan
Auth auth
Broadcast
Bus
Cache cache
Concurrency
Config config
Context
Cookie
Crypt encrypter
Date date
DB
Event
Feature
File files
Hash hash
Http
Image image
Lang translator
Log log
Mail mail.manager
Notification
Password auth.password
Pipeline pipeline
Process
Queue
RateLimiter
Redirect redirect
Redis redis
Request request
Response
Route
Schedule
Schema db.schema
Session session
Storage
URL url
Validator validator
View view
Vite
Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.