简体   繁体   中英

Trouble Understanding Facade in Laravel

For the most part I get the idea behind a facade and how the details of instantiating the object are hidden behind the static calls.

So if we take a look at this straight forward example here: Example

We see some code like this for the facade, which at this point just sets up some sort of Alias. At this point it seems the facade still knows nothing about the Superuser class.

class SuperuserFacade extends Facade
{
    protected static function getFacadeAccessor() { 
        return 'MyAlias'; 
    }
}

The logic is glued by the service provider here it seems:

class SuperuserServiceProvider extends ServiceProvider 
{
    public function register() {
        App::bind('MyAlias', function(){
            return new Superuser;
        });
    }
}

But it just binds the class the facade alias MyAlias . Why bother with that facade class and two separate files, can't we just do all this logic right in the service provider? Or alternatively in the facade provider having it just return the Superuser class?

It seems like we have the facade not really doing anything and then another file telling that facade what to do. Why have these concerns been separated?

The facade class is a simple proxy -- it directs any calls to the facade class to the root class, which is retrieved from the IoC container via the facade accessor (in this case, MyAlias ).

  1. I call Superuser::whoami()

  2. The Superuser facade goes "okay, I need to find the class that I'm a proxy for."

  3. The facade calls getFacadeAccessor() to determine what IoC binding to retrieve and subsequently call.

  4. The facade requests the MyAlias key from the IoC container. The container then returns an existing class if it has been built already, or it runs its bound closure which generates a new Superuser instance.

  5. Now that the facade knows what class it's passing calls to, it forwards the whoami() method call to the newly-returned Superuser instance, which then returns whatever it is designed to.

The service provider's register() method simply registers a binding to the IoC container, to be retrieved later by whatever needs it. That's it. MyAlias is a simple string key used to look up that binding.

The facade allows you to use an IoC-bound class as if it were a static class.

I recommend reading other articles about the concept, because the article you linked is both inaccurate and not very informational about why things work. Here is a better article by Chris Fidao .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM