How Is This Function Working? I Can't Understand Exactly What is Going On

StackOverflow https://stackoverflow.com/questions/21313606

  •  01-10-2022
  •  | 
  •  

Domanda

Here is a function definition of Set Helper class

public function singleton($key, $value)
    {
        $this->set($key, function ($c) use ($value) {
            static $object;

            if (null === $object) {
                $object = $value($c);
            }

            return $object;
        });
    }

and in this class the above mentioned function will be called like

 // Default environment
        $this->container->singleton('environment', function ($c) {
            return \Slim\Environment::getInstance();
        });

where $this->container represents the Set helper class.

È stato utile?

Soluzione

This appears to be an example of singleton factory using a plugin-strategy.

The API user declares "When I ask for the environment object, use the function function ($c) { return Slim\Environment::getInstance() } to generate it." The singleton method then takes care to ensure the API user only ever gets back the single instance of the environment object.

Mechanically, the singleton method associates a closure with a key. The closure manufactures a singleton object, given an anonymous function plug-in to actually do the instantiation. $value is the anonymous function and is responsible for whatever needs to go on to generate an instance of the object to become a singleton. singleton is responsible for ensuring that instantiation is every called once.

Side note: the difference between a closure and an anonymous function is meaninful in understanding what's going on with this method.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top