Learn about Laravel Facade

Tram Ho

Introduction

Surely anyone who has worked with the Laravel framework has used Facade. This is probably one of the most useful features in your software development process. With a simple and lightweight syntax, it can be used effectively even when we don’t really understand how they work. However, as a result, many people may misunderstand how Facades work. In this article we’ll go into more detail about Facades and how they actually work.

Table of contents

I. What is Facade?

II. How to use it?

III. How does it work?

IV. summary

I. What is Facade?

Facade is a Design Pattern for object oriented programming. Like a building facade, a facade in programming can be interpreted as an interface instead of complex architectures within a system. Thereby allows:

  • Easy to read and use by hiding complex library settings under a simple interface layer.
  • Reduces dependencies between blocks of code through interaction through the interface rather than the system itself.
  • Pack complex APIs into one neat system.

Facade in Laravel provides us with a simple “static” method interface that makes it easy to understand the functionality of Laravel services like Auth, Mail, Notification, etc. but at the same time maintaining flexibility and capabilities. testing of a non-static method.

II. How to use it?

All Laravel Facades are defined in the IlluminateSupportFacades namespace and can be used as follows:

In addition to that, Laravel also includes Helper that helps in performing simple tasks like the facade.

For example:

List of Laravel Facades:

FacadeClassService Container Binding
AppIlluminate Foundation Applicationapp
ArtisanIlluminate Contracts Console Kernelartisan
AuthIlluminate Auth AuthManagerauth
Auth (Instance)Illuminate Contracts Auth Guardauth.driver
BladeIlluminate View Compilers BladeCompilerblade.compiler
BroadcastIlluminate Contracts Broadcasting Factory
Broadcast (Instance)Illuminate Contracts Broadcasting Broadcaster
BusIlluminate Contracts Bus Dispatcher
CacheIlluminate Cache CacheManagercache
Cache (Instance)Illuminate Cache Repositorycache.store
ConfigIlluminate Config Repositoryconfig
CookiesIlluminate Cookie CookieJarcookie
CryptIlluminate Encryption Encrypterencrypter
DBIlluminate Database DatabaseManagerdb
DB (Instance)Illuminate Database Connectiondb.connection
EventIlluminate Events Dispatcherevents
FileIlluminate Filesystem Filesystemfiles
GateIlluminate Contracts Auth Access Gate
HashIlluminate Contracts Hashing Hasherhash
HttpIlluminate Http Client Factory
LangIlluminate Translation Translatortranslator
LogIlluminate Log LogManagerlog
MailIlluminate Mail Mailermailer
NotificationIlluminate Notifications ChannelManager
PasswordIlluminate Auth Passwords PasswordBrokerManagerauth.password
Password (Instance)Illuminate Auth Passwords PasswordBrokerauth.password.broker
QueueIlluminate Queue QueueManagerqueue
Queue (Instance)Illuminate Contracts Queue Queuequeue.connection
Queue (Base Class)Illuminate Queue Queue
RedirectIlluminate Routing Redirectorredirect
RedisIlluminate Redis RedisManagerredis
Redis (Instance)Illuminate Redis Connections Connectionredis.connection
RequestIlluminate Http Requestrequest
ResponseIlluminate Contracts Routing ResponseFactory
Response (Instance)Illuminate Http Response
RouteIlluminate Routing Routerrouter
SchemaIlluminate Database Schema Builder
SessionIlluminate Session SessionManagersession
Session (Instance)Illuminate Session Storesession.store
StorageIlluminate Filesystem FilesystemManagerfilesystem
Storage (Instance)Illuminate Contracts Filesystem Filesystemfilesystem.disk
URLIlluminate Routing UrlGeneratorurl
ValidatorIlluminate Validation Factoryvalidator
Validator (Instance)Illuminate Validation Validator
ViewIlluminate View Factoryview
View (Instance)Illuminate View View

III. How does it work?

In the example above we see the get() function of Facade Cache called as a static method: Cache::get('key') .

At first glance, Facade appears to be merely static methods called through classes like Mail , Auth , Cache , etc. but in reality, when we look at any of the implementation classes in the list. above we all find that they are completely normal methods.

For example: Facade Cache’s get() actually installed as follows.

So how can Laravel do this? To make it easier to understand how a Facade works, we’ll go into a concrete example of the facade cache .

Find the IlluminateSupportFacadesCache we find that it inherits the abstract class IlluminateSupportFacadesFacade and overwrite the getFacadeAccessor() function to return the container name corresponding to the facade.

For example:

Based on that Laravel will determine how this Facade will work. In CacheServiceProvider , an instance of CacheManager has been bound to the cache container using the Service Container. When the facade is called, the instance will be ressolved through the resolveFacadeInstance() function instead of complicatedly initializing the required services. Thereby, we can call CacheManager ‘s get('key') function through Cache as follows:

When a user calls a static function that does not exist get('key') of the Cache facade as above, PHP will execute the magic method __callStatic() takes two values ​​including the method name and the parameter passed.

For example: When calling the method Cache::get('key') the __callStatic() function will have $method get and $args as 'key' .

Here Facade will take out the instance of the corresponding service and make a call to the non-static function as a regular method.

As we can see through the above example, by cleverly using the __callStatic() magic method in conjunction with the Service Container, Facade provides a simple, easy-to-use interface for Laravel services but still maintains the advantages of non-static methods like when we do DI.

IV. summary

So here we went into detail how Facade works, an extremely useful tool in software development using the Laravel framework. If there is unclear content, expect everyone to comment to improve the article.

References

Laravel Documentation Facade: https://laravel.com/docs/8.x/facades#introduction

Laravel Documentation Service Container: https://laravel.com/docs/8.x/container

Facade Pattern: http://wiki.c2.com/?FacadePattern

PHP Magic method: https://www.php.net/manual/en/language.oop5.overloading.php#object.callstatic

Share the news now

Source : Viblo