简体   繁体   中英

how “request->getBody” works in slim

If I do a post, I can get content by doing $payload = json_decode($app->request->getBody());

But I cannot understand how request->getBody works in slim.

First, there's a magic method :

public function __get($name)
{
    return $this->container->get($name);
}

This will return a Slim\\Http\\Request object. That's fine for now.

$this->container is the Slim\\Helper\\Set, and this is the get function :

public function get($key, $default = null)
{
    if ($this->has($key)) {
        $isInvokable = is_object($this->data[$this->normalizeKey($key)]) && method_exists($this->data[$this->normalizeKey($key)], '__invoke');

        return $isInvokable ? $this->data[$this->normalizeKey($key)]($this) : $this->data[$this->normalizeKey($key)];
    }

    return $default;
}

$this->data[$this->normalizeKey($key)] is the same as $this->data['request'] , which is something of type "Closure" (not sure to understand this).

$isInvokable is true, so this is called :

$this->data[$this->normalizeKey($key)]($this)

What is this line doing ? Why the ($this) (Slim\\Helper\\Set) at the end ?

Especially, why the next function to be called is this :

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

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

        return $object;
    });
}

Why singleton($key, $value) ? It has never been called ! $key is not defined at the start of the function. Also what makes $ca Slim\\Helper\\Set, and $value a closure ?

And why the execution of only static $object makes the $object goes from unitialized to one of type Slim\\Http\\Request ?

Disclaimer: I'm not familiar with Slim. I'm just going by what you've posted.

Well, the Set->get() method tests, if the value in the data property array with the key $key can be invoked, and then does it, if true.

So $this->data[$this->normalizeKey($key)]($this) is calling a method with $this given as parameter and then Set->get() returns that method's return value.

A closure is also often called an " anonymous function ", which is a new feature as of PHP 5.3. Using an array as variable to call a function is available since PHP 5.4.

It allows you to pass around functions/methods as values, which is arguably the distinctive feature in functional programming .

Function singleton is called before in the initialization.

It is setting all $key to a function.

So, $this->data[$this->normalizeKey($key)]($this) is that function !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM