The confusion of the main Laravel method

I rummaged through the core of Laravel because I wanted to understand how this works. But I came up with a method that I just can’t envelop in my head even after 3 days. In start.php, the application binds to itself. So far, so good. But when I check the $ app-> share method, I get lost.

public function share(Closure $closure) { return function($container) use ($closure) { // We'll simply declare a static variable within the Closures and if // it has not been set we'll execute the given Closure to resolve // the value and return it back to the consumers of the method. static $object; if (is_null($object)) { $object = $closure($container); } return $object; }; } 

This method returns an anonymous function, which, when executed, returns an instance of the application. Am I seeing it right? Why is this? Why do you want to return a closure, not just an instance. This seems odd, but I'm pretty sure there is a reason;)

UPDATE String in start.php:

 $app['app'] = $app->share(function($app) { return $app; }); 

So, I think $ app ['app'] is a closing object. However, if I do get_class, the Illuminate \ Foundation \ Application class. In addition, there is also no way to execute it, since $ app'app 'will not work explicitly.

+4
source share
1 answer

$app not a normal array; it is actually an instance of Illuminate\Foundation\Application 1 , an extension of Illuminate\Container\Container 2 that implements ArrayAccess . But you already know this, since the share() method lives there.

A container associates keys with closures when they are accessed, the value is retrieved from memory, or, when first accessed, the associated closure is called and the return value is returned. When the key is installed on the container, it is wrapped in closure, if it is already closed.

This provides a consistent internal interface for the container, so the code does not constantly check its contents. It will also only load links that you actually use into memory. It is believed that the size of the lid is smaller than a fully loaded instance of the class. But after loading you get the opportunity to work with the same instance for the rest of the request.

Why the application is not registered in the container using instance() I do not know, although it is possible that it creates recursive links in the output of trace and dump.

+3
source

Source: https://habr.com/ru/post/948063/


All Articles