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

file

刻意练习,每日精进
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 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年前 评论

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