What is Facade in Laravel?

黄舟
Release: 2023-03-16 10:52:01
Original
2432 people have browsed it

Facade is actually a static proxy of a class in the container. It allows you to statically call any method of any object stored in the container. The following article mainly introduces you to the relevant information about the loading process and principle of Facade in Laravel. Friends in need can refer to it.

What is Facade in Laravel?

The definition given by the official document

"Facades provide a " Static" interface. Laravel comes with many Facades that provide access to most features. Laravel Facades are actually "static proxies" for the underlying classes in the service container. Compared with traditional static methods, they can provide more flexible, easier to test, and more elegant syntax when used. ”

You don’t have to use a long list of namespaces or instantiate the object to access the specific methods of the object.

use Config;

class Test
{
 public function index()
 {
 return Config::get('app.name');
 }
}
Copy after login

Facade startup and registration

Facade's startup boot is registered in Illuminate\Foundation\Bootstrap\RegisterFacades

public function bootstrap(Application $app)
{
 Facade::clearResolvedInstances();
 Facade::setFacadeApplication($app);

 AliasLoader::getInstance(array_merge(
 $app->make('config')->get('app.aliases', []),
 $app->make(PackageManifest::class)->aliases()
 ))->register();
}
Copy after login

The default alias configuration is read from aliases under the app configuration file. PackageManifest is a new package automatic discovery rule in laravel 5.5. Here we do not consider the alias provided by the PackageManifest package for the time being.

Among them, array_merge returns an array in the following format:

 "App" => "Illuminate\Support\Facades\App"
 "Artisan" => "Illuminate\Support\Facades\Artisan"
 "Auth" => "Illuminate\Support\Facades\Auth"
 "Blade" => "Illuminate\Support\Facades\Blade"
 ...
Copy after login

The above code All facades will be registered for automatic loading through AliasLoader. The core is php's spl_autoload_register.

 /**
 * Prepend the load method to the auto-loader stack.
 *
 * @return void
 */
 protected function register()
 {
 if (! $this->registered) {
  spl_autoload_register([$this, 'load'], true, true);

  $this->registered = true;
 }
 }
Copy after login

After the registration is completed, all subsequent use classes will be automatically loaded through the load function.

Note: When defining spl_autoload_register here, the last parameter is passed true. When this parameter is true, spl_autoload_register() will add the function to the head of the queue. Instead of the end of the queue (automatic loading is completed first through this function)

In other words,

<?php

use Config;
use App\User;

class Test
{
 public function index()
 {
 Config::get(&#39;app.name&#39;);
 new User();
 }
}
Copy after login

No matter whether we use a specific existing class (App\User) or Alias ​​(Config) will be automatically loaded first through the load function. When the function returns false, automatic loading will be completed by other automatic loading functions (such as composer psr-4).

In AliasLoader. In the load method, the class_alias function is mainly used to realize the automatic loading of aliases.

public function load($alias)
{
 if (isset($this->aliases[$alias])) {
 return class_alias($this->aliases[$alias], $alias);
 }
}
Copy after login

Regarding class_alias, here is an official example:

class foo { }

class_alias(&#39;foo&#39;, &#39;bar&#39;);

$a = new foo;
$b = new bar;

// the objects are the same
var_dump($a == $b, $a === $b); //true
var_dump($a instanceof $b); //false

// the classes are the same
var_dump($a instanceof foo); //true
var_dump($a instanceof bar); //true

var_dump($b instanceof foo); //true
var_dump($b instanceof bar); //true
Copy after login

Loading of Facade

When we use Facade, such as:

<?php

use Config;

class Test
{
 public function index()
 {
 Config::get(&#39;app.name&#39;);
 }
}
Copy after login

The Illuminate\Support\Facades\Config class is actually loaded (because we have registered class_alias), which is equivalent to:

<?php

use Illuminate\Support\Facades\Config;

class Test
{
 public function index()
 {
  Config::get(&#39;app.name&#39;);
 }
}
Copy after login

All Facades inherit from the Illuminate\Support\Facades\Facade class, and a __callStatic method is defined in this base class, so that we can easily use Facade (without instantiation).

<?php

public static function __callStatic($method, $args)
{
 $instance = static::getFacadeRoot();

 if (! $instance) {
  throw new RuntimeException(&#39;A facade root has not been set.&#39;);
 }

 return $instance->$method(...$args);
}
Copy after login

The getFacadeRoot method is used to obtain the specific instance column of the alias class. We know that all Facade classes need to define a getFacadeAccessor method. Possible return values ​​of this method are:

  • String type string (such as config, db)

  • String type string-like ( Such as App\Service\SomeService)

  • Object specific instantiated object

  • Closure closure

For example, the getFacadeAccessor method of Config Facade is as follows:

protected static function getFacadeAccessor()
{
 return &#39;config&#39;;
}
Copy after login

The getFacadeRoot method will retrieve the corresponding real column object from the container based on the return value of getFacadeAccessor() .

public static function getFacadeRoot()
{
 $name = static::getFacadeAccessor();
 
 if (is_object($name)) {
  return $name;
 }

 if (isset(static::$resolvedInstance[$name])) {
  return static::$resolvedInstance[$name];
 }

 return static::$resolvedInstance[$name] = static::$app[$name];
}
Copy after login

Since the actual column of config has been registered in the APP container

<?php
//Illuminate\Foundation\Bootstrap/LoadConfiguration

$app->instance(&#39;config&#39;, $config = new Repository($items));
Copy after login

So \Config::get('app.name', 'dafault) actually accessed It is the get('app.name', 'default') method of the Repository actual column.

For more related knowledge, please visit PHP Chinese website! !

The above is the detailed content of What is Facade in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!