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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top