这里为什么是集合,不是 Cache::put () 第二个参数是数组吗,为啥要转换成集合数据

file

刻意练习,每日精进
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 1
长日将尽

Cache::put() 实际上调用的是 \Illuminate\Cache\Repository.php 中的 put() 方法:

/**
 * Store an item in the cache.
 *
 * @param  string  $key
 * @param  mixed   $value
 * @param  \DateTimeInterface|\DateInterval|float|int|null  $minutes
 * @return void
 */
public function put($key, $value, $minutes = null)
{
    if (is_array($key)) {
        $this->putMany($key, $value);
        return;
    }
    if (! is_null($minutes = $this->getMinutes($minutes))) {
        $this->store->put($this->itemKey($key), $value, $minutes);
        $this->event(new KeyWritten($key, $value, $minutes));
    }
}

看代码,并没有规定第二个参数必须是数组,实际上都可以。我把教程中的代码修改成这样,使用数组保存用户实体,结果也是正常的:

$active_users = array(); // 使用数组
foreach ($users as $user_id => $user) {
    // 尝试查找用户
    $user = $this->find($user_id);
    // 如果数据库里有该用户的话
    if ($user) {
        // 将此用户实体放入数组的末尾
        array_push($active_users, $user);
    }
}
5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!