【问题标题】:Laravel cache::remember - cannot serialize closureLaravel cache::remember - 无法序列化闭包
【发布时间】:2020-05-03 16:19:39
【问题描述】:

我在尝试使用缓存时遇到以下异常:

但在 Laravel 文档 (https://laravel.com/docs/5.7/cache) 中,他们在示例中使用了闭包:

非常感谢任何帮助......已经用谷歌搜索了它,人们似乎遇到了永远()闭包不可序列化的问题(但建议的解决方案对我不起作用)

/**
     * @param string $guid
     * @return Account
     */
    public function getAccount(string $guid): Account
    {
        $key = md5(sprintf('xero/accounts[guid="%s"]', $guid));
        return $this->cache->remember($key, Carbon::now()->addHour(), function () use ($guid) {
            return $this->xero->loadByGUID(Account::class, $guid);
        });
    }

我现在也尝试这样做(以绕过将闭包传递给 cache::remember fxn):

public function getAccount(string $guid): Account
    {
        $key = md5(sprintf('xero/accounts[guid="%s"]', $guid));

        $account = $this->cache->get($key);
        if ($account === null) {
            //dump('account not found, storing in cache...');
            /** @var Account $account */
            $account = $this->xero->loadByGUID(Account::class, $guid);
            $this->cache->put($key, $account, Carbon::now()->addHour());
        }
    }

但在 '$this->cache->put($key, $account, Carbon::now()->addHour());' 行仍然出现相同的错误(无法序列化 Closure)

$account 对象的类型为:use XeroPHP\Models\Accounting\Account; (来自https://github.com/calcinai/xero-php

【问题讨论】:

  • 请分享您正在使用的代码
  • 还有你想缓存什么类型的元素?
  • 这可能对你有帮助吗:github.com/laravel/framework/issues/…
  • 谢谢@ChristopheHubert 我以前看过那个链接。您最后是在谈论 DanRichard 的解决方案吗?
  • 是的,这是正确的 - 因为它与队列有关,所以它似乎与您的问题有关

标签: laravel caching laravel-5.7


【解决方案1】:

模型包含对包含 Guzzle 客户端实例的 Xero 应用程序的引用,该实例本身具有包含闭包的属性。 PHP 序列化函数无法序列化闭包:https://3v4l.org/1MIpd

当您存储和检索模型时,可能会调用 toStringArray 和 fromStringArray。

(完全归功于 Josh-G:https://github.com/calcinai/xero-php/issues/734

【讨论】:

    猜你喜欢
    • 2016-04-04
    • 2017-12-29
    • 2021-08-29
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2019-11-11
    • 2020-08-27
    相关资源
    最近更新 更多