Search

Laravel Facades Part Two: Using Facades

November 21, 2016 —John Koster

This article is part of a four part series all about Laravel facades. Each of the parts are listed below:

Laravel's facades are used just like any other static class, with the exception that facades are redirecting method calls to an actual class instance. Facades are typically imported at the top of the source file, along with any other classes that are required.

For example, using a facade to retrieve an item from the cache:

1<?php
2 
3namespace App\Http\Controllers;
4 
5use Illuminate\Support\Facades\Cache;
6 
7class ExampleController extends Controller {
8 
9 public function getIndex()
10 {
11 $cachedItem = Cache::get('some_cache_item');
12 }
13 
14}

The alternative is to inject the cache repository directly into the controller:

Dependency injection is not the only alternative to using facades, it is, however, arguably the most common in Laravel projects.

1<?php
2 
3namespace App\Http\Controllers;
4 
5use Illuminate\Cache\Repository as CacheRepository;
6 
7class ExampleController extends Controller {
8 
9 /**
10 * The cache repository.
11 
12 * @var CacheRepository
13 */
14 protected $cacheRepository = null;
15 
16 public function __construct(CacheRepository $cacheRepository)
17 {
18 $this->cacheRepository = $cacheRepository;
19 }
20 
21 public function getIndex()
22 {
23 $cachedItem = $this->cacheRepository->get('some_cache_item');
24 }
25 
26}

Both code examples would accomplish the same thing: retrieve some_cache_item from the cache storage. The facade example allows for shorter code, and code that is definitely easier to follow along with. The second example has its own advantages too, which will not be covered in this section.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.