


Detailed explanation of the loading process and principle of Facade in Laravel
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. This article mainly introduces you to the loading process and principle of Facade in Laravel. For relevant information, friends in need can refer to it. I hope to be helpful.
Preface
This article mainly introduces the relevant content about the Facade loading process and principles in Laravel, and shares it for your reference and study. Not much to say below, let’s take a look at the detailed introduction.
Introduction
Facades (pronounced: /fəˈsäd/) provide a " Static" interface. You don't have to use a bunch of namespaces or instantiate the object to access its specific methods.
use Config; class Test { public function index() { return Config::get('app.name'); } }
Facade startup and registration
Facade 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(); }
The default alias configuration is read from aliases under the app configuration file. PackageManifest is a new package automatic discovery rule added by laravel 5.5. Here we do not consider the aliases 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" ...
The above code will register all facades 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; } }
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 tail. (This function is used first to complete automatic loading)
In other words,
<?php use Config; use App\User; class Test { public function index() { Config::get('app.name'); new User(); } }
No matter what we use is a specific existing class (App\User) or an alias (Config), Automatic loading will be completed 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 the load method of AliasLoader, the class_alias function is mainly used to implement automatic loading of aliases.
public function load($alias) { if (isset($this->aliases[$alias])) { return class_alias($this->aliases[$alias], $alias); } }
About class_alias Here is an official example:
class foo { } class_alias('foo', 'bar'); $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
Loading of Facade
When we are in When using Facade, for example:
<?php use Config; class Test { public function index() { Config::get('app.name'); } }
actually loads the Illuminate\Support\Facades\Config class (because we have registered class_alias), which is equivalent to:
<?php use Illuminate\Support\Facades\Config; class Test { public function index() { Config::get('app.name'); } }
And all Facades are Inherited from the Illuminate\Support\Facades\Facade class, 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('A facade root has not been set.'); } return $instance->$method(...$args); }
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 'config'; }
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]; }
Since the actual column of config has been registered in the APP container
<?php //Illuminate\Foundation\Bootstrap/LoadConfiguration $app->instance('config', $config = new Repository($items));
, so \Config::get('app.name', 'dafault)
actually accessed It is the get('app.name', 'default')
method of the Repository actual column.
Related recommendations:
##Detailed explanation of Laravel using salt and password authentication by modifying Auth
Detailed explanation of Laravel’s localization module
Detailed explanation of how to rewrite resource routing in Laravel
The above is the detailed content of Detailed explanation of the loading process and principle of Facade in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
