Laravel Facades: When To Use Facades

When To Use Facades

Pay special attention to the size of your class so that its scope of responsibility stays narrow.

Facades Vs. Dependency Injection

Use Illuminate\Support\Facades\Cache;

Route::get('/cache', function () {
    return Cache::get('key');
});
Use Illuminate\Support\Facades\Cache;

/**
 * A basic functional test example.
 *
 * @return void
 */
public function testBasicExample()
{
    Cache::shouldReceive('get')
         ->with('key')
         ->andReturn('value');

    $this->visit('/cache')
         ->see('value');
}

Since facades use dynamic methods to proxy method calls to objects resolved from the service container, we actually can test facades just as we would test an injected class instance.

Facades Vs. Helper Functions

Return View::make('profile');

return view('profile');
Route::get('/cache', function () {
    return cache('key');
});
Use Illuminate\Support\Facades\Cache;

/**
 * A basic functional test example.
 *
 * @return void
 */
public function testBasicExample()
{
    Cache::shouldReceive('get')
         ->with('key')
         ->andReturn('value');

    $this->visit('/cache')
         ->see('value');
}

There is absolutely no practical difference between facades and helper functions.

Laravel Facades: When To Use Facades — Structure map

Clickable & Draggable!

Laravel Facades: When To Use Facades — Related pages: