Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why create a facade in laravel instead of calling a method directly?

I'm just starting with laravel and want to understand this...

Lets say we have a class in our application:

namespace App\Tests;
class MyTest{

    public function sayHello($name){
        echo "Hello, $name!";
    }

    public static function anotherTest(){
        echo "another test...";
    }

}

What is the advantage of creating a facade and a service provider over just using it as

use App\Tests\MyTest;

//... controller declarations here ....

public function someaction(){

    $mt = new MyTest();
    $mt->sayHello('John');

    //or
    MyTest::anotherTest();

}

//... etc...
like image 892
CarlosCarucce Avatar asked Mar 17 '16 13:03

CarlosCarucce


1 Answers

A Facade in Laravel is only a convenient way to get an object from the Service Container and call a method on it.

So calling a Facade like this :

//access session using a Facade 
$value = Session::get('key'); 

Is like doing:

//access session directly from the Service Container
$value = $app->make('session')->get('key'); 

As the Facade resolves the session key out of the Service Container and call the method get on it

Once understood what a Facade does, you should understand what is the Service container and what are the benefits of using it

The Service Container in Laravel cloud be a Dependency Injection Container and a Registry for the application

The advantages of using a Service Container over creating manually your objects are stated in one of my previous answers and in the doc page, but briefly:

  • Capacity to manage class dependencies on object instantation
  • Binding of interfaces to concrete classes, so that when a interface is requested in your program, a concrete class is instantiated automatically by the service container. Changing the concrete class on the binding, will change the concrete objects instantiated through all your app
  • Possibility to create single intances and get them back later (Singleton)
like image 110
Moppo Avatar answered Oct 20 '22 08:10

Moppo