Jesper Andersen
Jesper Andersen

Reputation: 574

Facades vs. Classes with static methods in Laravel

I was looking around the Laravel framework and some of their products and I noticed that Cashier is using the Casheir class with static methods compared to Socialite, which is used as a facade.

What are the benefits/downsides of building it one or the other way, or is there none at all? I would like to build something myself, but I don't want to start building it as a class with static methods if building it as a facade is a better solution.

Upvotes: 3

Views: 2089

Answers (1)

Kent
Kent

Reputation: 176

When you may need multiple implementations, a single interface can be defined through facade to simplify the code

Building it as a class with static methods:

When you have multiple classes you have to do something like this:

CashierOne::method, CashierTwo::method ....

Used as a facade:

According to what you bind to the container to switch the implementation You only need to call through an interface:

// Define a Cashier Facade
class Cashier extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'cashier';
    }
}

// In CashServiceProvider
$this->app->singleton('cashier', function ($app) {
    return new CashierManager ($app);
});

// In CashierManager
public function gateway($name = null)
{
    // get cashier implementation by name
}

public function __call($method, $parameters)
{
    return $this->gateway()->$method(...$parameters);
}

// In Controller
Cashier::method

In addition, the facade is easier to test, check:

https://laravel.com/docs/5.8/facades#how-facades-work

Upvotes: 4

Related Questions