rameezmeans
rameezmeans

Reputation: 850

Laravel - Facade explanation and code example

whenever we call a Facade Method it involves Facade design pattern and it called for some hidden class by using Facade. for instance for File, if we call

File::get(public_path().'test.txt');

this will call the method in class

Illuminate\Filesystem\Filesystem

and in this class we will have get($path) method.

Now my question is how Facade Abstract Class is related to File and Filesystem and where Laravel is telling them to call get in Filesystem. is there some kind of register which i am missing ?? i want to find complete link.

Upvotes: 1

Views: 2302

Answers (1)

Mozammil
Mozammil

Reputation: 8750

If you go in your config/app.php, you will notice that there's an array called aliases which looks like this

'aliases' => [
    // 
    //
    //
    //
    'File' => Illuminate\Support\Facades\File::class, 
]; 

So, basically whenever you call File, the Service Container will try to resolve an instance of Illuminate\Support\Facades\File::class which is just a Facade.

If you look into Illuminate\Support\Facades\File::class, you will see that it contains only one method:

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

As you can see, it extends the Facade class and whenever a Facade is being resolved, Laravel will try to find a key in the Service Container that is equal to whatever is returned by getFacadeAccessor().

If you check the source of Illuminate\Filesystem\FilesystemServiceProvider, you will see this:

$this->app->singleton('files', function () {
    return new Filesystem;
});

As you can see, the key files is being bounded to a FileSystem implementation. So, that's how Laravel knows how to resolve the File facade.

Upvotes: 4

Related Questions