How To Create A Facade In Laravel

In this tutorial we're going to learn how to use and create your own Laravel facades.

What Is A Facade?

A facade provides a static way of accessing the Laravel service container. The service container allows you to instaniate classes via an alias. You can access the service container by using the app() or resolve() helper functions, passing in the alias for the class you want to return.

$client = app('api-client');

You can add new classes into the service container by using the bind method ont he app object into the AppServiceProvider on the register function.

$this->app->bind('api-client', Client::class);

A facade provides a static way of calling $client = app('api-client'); you can replace it with Client::get().

A facade underneath will call the __callStatic magic method which will instaniate the class from the service container. Therefore if you ever want to change the class which is returned from a facade you can replace the class in the service container.

The benefit you get of using facades is a memorable syntax for calling specific classes. For example in Laravel they have the Cache facade to provide an easy way of adding something into cache by using.

Cache::remember('name', 60, function () {
    // Cache this
});

This can be used at any point in your codebase and doesn't need to be injected into the class to use. Facades make it easy to test and mock or fake the functionality because we can override the class returned from the service container.

To check which facades you get with Laravel you can view it in the documentation here.

How To Test A Facade?

Using facades makes it very easy to test your code. The Laravel abstract facade class comes with a shouldReceive method that will allow you to make sure that the facade is called and how many times.

    public function testUsers()
    {
        Cache::shouldReceive('get')
                    ->once()
                    ->with('key')
                    ->andReturn('value');

        $response = $this->get('/users');

        // ...
    }

The above code will make sure that the Cache facade is called and it returns the correct value.

How To Create Your Own Facade?

To create your own facade you need very little code to get started. First you need a class for the facade and then another class of what will be instaniated from the facade. We'll build a facade that can be used to make an api call in your code.

<?php

namespace App\Facade;

use Illuminate\Support\Facades\Facade;

/**
 * Class ApiClient
 */
class ApiClient extends Facade
{
    /**
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'api-client';
    }
}

Then add the entry into your AppServiceProvider.

$this->app->bind('api-client', Client::class);

You can create the Client class for the API like any normal class.

class Client
{
    public function get($url) 
	{
	    // Make API GET request
	}
}

Now we can use the ApiClient anywhere in our code statically to make a call to the API.

class HomeController
{
	public function index () 
	{
		$posts = ApiClient::get('/posts');
	}
}

With the shouldReceive method we can use this to make sure that get is called.

public function testPosts()
{
	ApiClient::shouldReceive('get')
    	->once()
        ->with('/posts')
        ->andReturn(new Collection);

	$response = $this->get('/posts');

	// ...
}

That's all the code you need to use and test facades in your own application.

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring