2Hats . 3 minutes

Laravel Facades Part 1 – What they are and how they work

Facades allow us to call classes defined under the service container in an elegant and expressive way – as “static” interfaces. If you are a Laravel developer, chances are that you are using Facades all the time. You may not just know that yet. Laravel ships in with many facades like Hash, Input, Mail etc. Let’s take the example of Hash facade and try to figure out how it works.

You may be familiar with something like this,

If you search for a class named Hash, you won’t find it. Go to app/config.php and scroll down to the bottom where the class Aliases are defined. There you will see this,

Take a look at that file,

This file has just one method in it,

Go back to the app/config.php file again and take a look at the providers list, you can see that a Service provider has been added for Hashing

Take a look at the service provider under vendorlaravelframeworksrcIlluminateHashingHashServiceProvider.php
You will see this under the register method,

It defines that the class BcryptHasher is associated with the hash facade ( the value returned by the getFacadeAccessor method in the Hash Facade file we saw above). Let’s try to find that class

 

You can see it here

But wait, the make method is not static but we are able to call it like

Underneath the hood, Laravel makes use of the callStatic magic method and reflection to make this happen. You can read through those if you are not familiar with the terms
http://php.net/manual/en/language.oop5.overloading.php#object.callstatic

http://culttt.com/2014/07/02/reflection-php/

Let’s continue digging in. The BcryptHasher implements HasherContract. Its imported at the top of the file,

It’s a nice and clean interface that defines the contract which means every one of its implementations that should satisfy this contract.

Suppose you wish to implement your own hashing function or change the existing Bcrypter class. Just go to the HashServiceProvider and change the class there,

Clean and simple! The very reason we all love Laravel.

As you can see Facades are great if you know how to use them. You have an elegant syntax and flexibility while not compromising on anything. In part 2, we will learn how to create your own custom Facades.

blog
Greetings! I'm Aneesh Sreedharan, CEO of 2Hats Logic Solutions. At 2Hats Logic Solutions, we are dedicated to providing technical expertise and resolving your concerns in the world of technology. Our blog page serves as a resource where we share insights and experiences, offering valuable perspectives on your queries.
Aneesh ceo
Aneesh Sreedharan
Founder & CEO, 2Hats Logic Solutions
Subscribe to our Newsletter
Arsha Content writer

    Stay In The Loop!

    Subscribe to our newsletter and learn about the latest digital trends.