Facades in Laravel. Why and How?

Facades in Laravel. Why and How?

  1. view('home'); , this is the helper function in laravel, and
  2. View::make('home'); , this is the direct class reference that we can use, still without importing it.

So, What is happening here?

There is a little magic behind the scene which is the laravel service container(IoC). It loads all the classes before loading the application, so at run time, they are available for us to use. You can assume how many classes you have to import if you were using core PHP to run something like Laravel. There has to be a way around this.

What are Facades?

Facades are a way to register your class and its functions with the Laravel Container, so they are available everywhere after getting resolved by Reflection.

Why to use Facades?

Facades have many benefits like you don’t have to remember long class names, which needs to be imported or injected before using them.

How To Make Use of Facades or probably create your own?

First we need a class with some function, create MyFacade.php class, in app folder.

<?php

namespace App;

class MyFacade
{
public function getName()
{
return 'Facades are awesome';
}
}

use App\MyFacade;

Route::get('/', function () {

$facade = new MyFacade();
return $facade->getName();
});

<?php

namespace App\Facades;

use \Illuminate\Support\Facades\Facade;

class MyFacade extends Facade
{
public static function getFacadeAccessor()
{
return 'myfacade';
}
}

/**
* Register any application services.
*
* @return void
*/
public function register()
{
app()->bind('myfacade', function() {
return new \App\MyFacade;
});
}

//use App\MyFacade; Do not need to import the class

Route::get('/', function () {

//$facade = new MyFacade(); Do not need to make object
return MyFacade::getName(); //See the magic, in your browser.
});