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

file

刻意练习,每日精进
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 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年前 评论

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