douji0588 2015-10-28 16:54
浏览 72

“请求 - > getBody”如何在苗条中运作

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 $c a 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 ?

  • 写回答

2条回答 默认 最新

  • dousong8187 2015-10-28 17:22
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?